home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / efs / dired.el.z / dired.el
Encoding:
Text File  |  1998-05-21  |  235.8 KB  |  6,469 lines

  1.  ; -*- Emacs-Lisp -*-
  2. ;; DIRED commands for Emacs.
  3. ;; Copyright (C) 1985, 1986, 1991 Free Software Foundation, Inc.
  4. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  5. ;;
  6. ;; File:          dired.el
  7. ;; RCS:           
  8. ;; Dired Version: #Revision: 7.9 $
  9. ;; Description:   The DIRectory EDitor is for manipulating, and running
  10. ;;                commands on files in a directory.
  11. ;; Authors:       FSF,
  12. ;;                Sebastian Kremer <sk@thp.uni-koeln.de>,
  13. ;;                Sandy Rutherford <sandy@ibm550.sissa.it>
  14. ;;                Cast of thousands...
  15. ;;
  16. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  17.  
  18. ;; This program is free software; you can redistribute it and/or modify
  19. ;; it under the terms of the GNU General Public License as published by
  20. ;; the Free Software Foundation; either version 1, or (at your option)
  21. ;; any later version.
  22.  
  23. ;; This program is distributed in the hope that it will be useful,
  24. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  26. ;; GNU General Public License for more details.
  27.  
  28. ;; You should have received a copy of the GNU General Public License
  29. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  30. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  31.  
  32. ;; Rewritten in 1990/1991 to add tree features, file marking and
  33. ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
  34. ;; 7-1993: Added special features for efs interaction and upgraded to Emacs 19.
  35. ;;         Sandy Rutherford <sandy@ibm550.sissa.it>
  36.  
  37. ;;; Dired Version
  38.  
  39. (defconst dired-version (substring "#Revision: 7.9 $" 11 -2)
  40.   "The revision number of Tree Dired (as a string).
  41.  
  42. Don't forget to mention this when reporting bugs to:
  43.    
  44.    efs-bugs@cuckoo.hpl.hp.com")
  45.  
  46. ;; Global key bindings:
  47. ;; --------------------
  48. ;;
  49. ;; By convention, dired uses the following global key-bindings.
  50. ;; These may or may not already be set up in your local emacs. If not
  51. ;; then you will need to add them to your .emacs file, or the system
  52. ;; default.el file. We don't set them automatically here, as users may
  53. ;; have individual preferences.
  54. ;;
  55. ;; (define-key ctl-x-map "d" 'dired)
  56. ;; (define-key ctl-x-4-map "d" 'dired-other-window)
  57. ;; (define-key ctl-x-map "\C-j" 'dired-jump-back)
  58. ;; (define-key ctl-x-4-map "\C-j" 'dired-jump-back-other-window)
  59. ;; 
  60. ;; For V19 emacs only. (Make sure that the ctl-x-5-map exists.)
  61. ;; (define-key ctl-x-5-map "d" 'dired-other-frame)
  62. ;; (define-key Ctl-x-5-map "\C-j" 'dired-jump-back-other-frame)
  63.  
  64.  
  65. ;;; Grok the current emacs version
  66. ;;
  67. ;; Hopefully these two variables provide us with enough version sensitivity.
  68.  
  69. ;; Make sure that we have a frame-width function
  70. (or (fboundp 'frame-width) (fset 'frame-width 'screen-width))
  71.  
  72. ;;; Requirements and provisions
  73.  
  74. (provide 'dired)
  75. (require 'backquote) ; For macros.
  76.  
  77. ;; Compatibility requirements for the file-name-handler-alist.
  78. ;; Testing against the string `Lucid' breaks InfoDock.  How many years has
  79. ;; it been since Lucid went away?
  80. (let ((lucid-p (string-match "XEmacs" emacs-version))
  81.       ver subver)
  82.   (or (string-match "^\\([0-9]+\\)\\.\\([0-9]+\\)" emacs-version)
  83.       (error "dired does not work with emacs version %s" emacs-version))
  84.   (setq ver (string-to-int (substring emacs-version (match-beginning 1)
  85.                       (match-end 1)))
  86.     subver (string-to-int (substring emacs-version (match-beginning 2)
  87.                      (match-end 2))))
  88.   (cond
  89.    ((= ver 18)
  90.     (require 'emacs-19)
  91.     (require 'fn-handler))
  92.    ((and (= ver 19) (if lucid-p (< subver 10) (< subver 23)))
  93.     (require 'fn-handler))
  94.    ((< ver 18)
  95.     (error "dired does not work with emacs version %s" emacs-version))))
  96.  
  97. ;; We duplicate default-dir stuff to avoid its overwrites unless
  98. ;; they are explicitly requested.
  99.  
  100. (defvar default-directory-function nil
  101.   "A function to call to compute the default-directory for the current buffer.
  102. If this is nil, the function default-directory will return the value of the
  103. variable default-directory.
  104. Buffer local.")
  105. (make-variable-buffer-local 'default-directory-function)
  106.  
  107. ;;;###autoload
  108. (defun default-directory ()
  109.   " Returns the default-directory for the current buffer.
  110. Will use the variable default-directory-function if it non-nil."
  111.   (if default-directory-function
  112.       (funcall default-directory-function)
  113.     (if (string-match "XEmacs" emacs-version)
  114.     (abbreviate-file-name default-directory t)
  115.       (abbreviate-file-name default-directory))))
  116.  
  117. ;;;;----------------------------------------------------------------
  118. ;;;; Customizable variables
  119. ;;;;----------------------------------------------------------------
  120. ;;
  121. ;; The funny comments are for autoload.el, to automagically update
  122. ;; loaddefs.
  123.  
  124. ;;; Variables for compressing files.
  125.  
  126. ;;;###autoload
  127. (defvar dired-compression-method 'compress
  128.   "*Type of compression program to use.
  129. Give as a symbol.
  130. Currently-recognized methods are: gzip pack compact compress.
  131. To change this variable use \\[dired-do-compress] with a zero prefix.")
  132.  
  133. ;;;###autoload
  134. (defvar dired-compression-method-alist
  135.   '((gzip     ".gz" ("gzip")          ("gzip" "-d") "-f")
  136.     ;; Put compress before pack, so that it wins out if we are using
  137.     ;; efs to work on a case insensitive OS. The -f flag does
  138.     ;; two things in compress. No harm in giving it twice.
  139.     (compress ".Z"  ("compress" "-f") ("compress" "-d") "-f")
  140.     ;; pack support may not work well.  pack is too chatty and there is no way
  141.     ;; to force overwrites.
  142.     (pack     ".z"  ("pack" "-f")     ("unpack"))
  143.     (compact  ".C"  ("compact")       ("uncompact")))
  144.   
  145.   "*Association list of compression method descriptions.
  146.  Each element of the table should be a list of the form
  147.  
  148.      \(compress-type extension (compress-args) (decompress-args) force-flag\)
  149.  
  150.  where 
  151.    `compress-type' is a unique symbol in the alist to which
  152.       `dired-compression-method' can be set;
  153.    `extension' is the file extension (as a string) used by files compressed
  154.       by this method;
  155.    `compress-args' is a list of the path of the compression program and
  156.       flags to pass as separate arguments;
  157.    `decompress-args' is a list of the path of the decompression
  158.       program and flags to pass as separate arguments.
  159.    `force-flag' is the switch to pass to the command to force overwriting
  160.       of existing files.
  161.  
  162.  For example:
  163.  
  164.    \(setq dired-compression-method-alist
  165.          \(cons '\(frobnicate \".frob\" \(\"frob\"\) \(\"frob\" \"-d\"\) \"-f\"\)
  166.                dired-compression-method-alist\)\)
  167.    => \(\(frobnicate \".frob\" \(\"frob\"\) \(\"frob\" \"-d\"\)\) 
  168.        \(gzip \".gz\" \(\"gzip\"\) \(\"gunzip\"\)\)
  169.        ...\)
  170.  
  171.  See also: dired-compression-method <V>")
  172.  
  173. ;;; Variables for the ls program.
  174.  
  175. ;;;###autoload
  176. (defvar dired-ls-program "ls"
  177.   "*Absolute or relative name of the ls program used by dired.")
  178.  
  179. ;;;###autoload
  180. (defvar dired-listing-switches "-al"
  181.   "*Switches passed to ls for dired. MUST contain the `l' option.
  182. Can contain even `F', `b', `i' and `s'.")
  183.  
  184. (defvar dired-ls-F-marks-symlinks
  185.   (memq system-type '(aix-v3 hpux silicon-graphics-unix))
  186.   ;; Both SunOS and Ultrix have system-type berkeley-unix. But
  187.   ;; SunOS doesn't mark symlinks, but Ultrix does. Therefore,
  188.   ;; can't grok this case.
  189.   "*Informs dired about how ls -lF marks symbolic links.
  190. Set this to t if `dired-ls-program' with -lF marks the name of the symbolic
  191. link itself with a trailing @.
  192.  
  193. For example: If foo is a link pointing to bar, and \"ls -F bar\" gives 
  194.  
  195.      ...   bar -> foo
  196.  
  197. set this variable to nil. If it gives
  198.     
  199.       ...   bar@ -> foo
  200.  
  201. set this variable to t.
  202.  
  203. Dired checks if there is really a @ appended.  Thus, if you have a
  204. marking ls program on one host and a non-marking on another host, and
  205. don't care about symbolic links which really end in a @, you can
  206. always set this variable to t.
  207.  
  208. If you use efs, it will make this variable buffer-local, and control
  209. it according to its assessment of how the remote host marks symbolic
  210. links.")
  211.  
  212. (defvar dired-show-ls-switches nil
  213.   "*If non-nil dired will show the dired ls switches on the modeline.
  214. If nil, it will indicate how the files are sorted by either \"by name\" or
  215. \"by date\". If it is unable to recognize the sorting defined by the switches,
  216. then the switches will be shown explicitly on the modeline, regardless of the
  217. setting of this variable.")
  218.  
  219. ;;; Variables for other unix utility programs.
  220.  
  221. ;; For most program names, don't use absolute paths so that dired
  222. ;; uses the user's value of the environment variable PATH. chown is
  223. ;; an exception as it is not always in the PATH.
  224.  
  225. ;;;###autoload
  226. (defvar dired-chown-program
  227.   (if (memq system-type '(hpux dgux usg-unix-v linux)) "chown" "/etc/chown")
  228.   "*Name of chown command (usually `chown' or `/etc/chown').")
  229.  
  230. ;;;###autoload
  231. (defvar dired-gnutar-program nil
  232.   "*If non-nil, name of the GNU tar executable (e.g. \"tar\" or \"gnutar\").
  233. GNU tar's `z' switch is used for compressed tar files.
  234. If you don't have GNU tar, set this to nil: a pipe using `zcat' is then used.")
  235.  
  236. ;;;###autoload
  237. (defvar dired-unshar-program nil
  238.   "*Set to the name of the unshar program, if you have it.")
  239.  
  240. ;;; Markers
  241.  
  242. (defvar dired-keep-marker-rename t
  243.   ;; Use t as default so that moved files `take their markers with them'
  244.     "*Controls marking of renamed files.
  245. If t, files keep their previous marks when they are renamed.
  246. If a character, renamed files (whether previously marked or not)
  247. are afterward marked with that character.")
  248.  
  249. (defvar dired-keep-marker-compress t
  250.   "*Controls marking of compressed or uncompressed files.
  251. If t, files keep their previous marks when they are compressed.
  252. If a character, compressed or uncompressed files (whether previously
  253. marked or not) are afterward marked with that character.")
  254.  
  255. (defvar dired-keep-marker-uucode ?U
  256.   "*Controls marking of uuencoded or uudecoded files.
  257. If t, files keep their previous marks when they are uuencoded.
  258. If a character, uuencoded or uudecoded files (whether previously
  259. marked or not) are afterward marked with that character.")
  260.  
  261. (defvar dired-keep-marker-copy ?C
  262.   "*Controls marking of copied files.
  263. If t, copied files are marked if and as the corresponding original files were.
  264. If a character, copied files are unconditionally marked with that character.")
  265.  
  266. (defvar dired-keep-marker-hardlink ?H
  267.   "*Controls marking of newly made hard links.
  268. If t, they are marked if and as the files linked to were marked.
  269. If a character, new links are unconditionally marked with that character.")
  270.  
  271. (defvar dired-keep-marker-symlink ?S
  272.   "*Controls marking of newly made symbolic links.
  273. If t, they are marked if and as the files linked to were marked.
  274. If a character, new links are unconditionally marked with that character.")
  275.  
  276. (defvar dired-keep-marker-kill ?K
  277.   "*When killed file lines are redisplayed, they will have this marker.
  278. Setting this to nil means that they will not have any marker.")
  279.  
  280. (defvar dired-failed-marker-shell ?!
  281.   "*If non-nil, a character with which to mark files of failed shell commands.
  282. Applies to the command `dired-do-shell-command'.  Files for which the shell
  283. command has a nonzero exit status will be marked with this character")
  284.  
  285. ;;; Behavioral Variables
  286.  
  287. ;;;###autoload
  288. (defvar dired-local-variables-file ".dired"
  289.   "*If non-nil, filename for local variables for Dired.
  290. If Dired finds a file with that name in the current directory, it will
  291. temporarily insert it into the dired buffer and run `hack-local-variables'.
  292.  
  293. Type \\[info] and `g' `(emacs)File Variables' `RET' for more info on
  294. local variables.")
  295.  
  296. ;; Usually defined in files.el. Define here anyway, to be safe.
  297. ;;;###autoload
  298. (defvar dired-kept-versions 2
  299.   "*When cleaning directory, number of versions to keep.")
  300.  
  301. ;;;###autoload
  302. (defvar dired-find-subdir nil
  303.   "*Determines whether dired tries to lookup a subdir in existing buffers.
  304. If non-nil, dired does not make a new buffer for a directory if it can be
  305. found (perhaps as subdir) in some existing dired buffer. If there are several
  306. dired buffers for a directory, then the most recently used one is chosen.
  307.  
  308. Dired avoids switching to the current buffer, so that if you have
  309. a normal and a wildcard buffer for the same directory, C-x d RET will
  310. toggle between those two.")
  311.  
  312. ;;;###autoload
  313. (defvar dired-use-file-transformers t
  314.   "*Determines whether dired uses file transformers.
  315. If non-nil `dired-do-shell-command' will apply file transformers to file names.
  316. See \\[describe-function] for dired-do-shell-command for more information.")
  317.  
  318. ;;;###autoload
  319. (defvar dired-dwim-target nil
  320.   "*If non-nil, dired tries to guess a default target directory.
  321. This means that if there is a dired buffer displayed in the next window,
  322. use its current subdir, instead of the current subdir of this dired buffer.
  323. The target is put in the prompt for file copy, rename, etc.")
  324.  
  325. ;;;###autoload
  326. (defvar dired-copy-preserve-time nil
  327.   "*If non-nil, Dired preserves the last-modified time in a file copy.
  328. \(This works on only some systems.)\\<dired-mode-map>
  329. Use `\\[dired-do-copy]' with a zero prefix argument to toggle its value.")
  330.  
  331. ;;;###autoload
  332. (defvar dired-no-confirm nil
  333.   "*If non-nil, a list of symbols for commands dired should not confirm.
  334. It can be a sublist of
  335.  
  336.   '(byte-compile chgrp chmod chown compress copy delete hardlink load
  337.     move print shell symlink uncompress recursive-delete kill-file-buffer
  338.     kill-dired-buffer patch create-top-dir revert-subdirs)
  339.  
  340. The meanings of most of the symbols are obvious.  A few exceptions:
  341.  
  342.     'compress applies to compression or decompression by any of the 
  343.      compression program in `dired-compression-method-alist'.
  344.  
  345.     'kill-dired-buffer applies to offering to kill dired buffers for
  346.      directories which have been deleted.
  347.  
  348.     'kill-file-buffer applies to offering to kill buffers visiting files
  349.      which have been deleted.
  350.  
  351.     'recursive-delete applies to recursively deleting non-empty
  352.      directories, and all of their contents.
  353.  
  354.     'create-top-dir applies to `dired-up-directory' creating a new top level
  355.      directory for the dired buffer.
  356.  
  357.     'revert-subdirs applies to re-reading subdirectories which have 
  358.      been modified on disk.
  359.  
  360. Note that this list also applies to remote files accessed with efs
  361. or ange-ftp.")
  362.  
  363. ;;;###autoload
  364. (defvar dired-backup-if-overwrite nil
  365.   "*Non-nil if Dired should ask about making backups before overwriting files.
  366. Special value 'always suppresses confirmation.")
  367.  
  368. ;;;###autoload
  369. (defvar dired-omit-files nil
  370.   "*If non-nil un-interesting files will be omitted from this dired buffer.
  371. Use \\[dired-omit-toggle] to see these files. (buffer local)")
  372. (make-variable-buffer-local 'dired-omit-files)
  373.  
  374. ;;;###autoload
  375. (defvar dired-mail-reader 'vm
  376.   "*Mail reader used by dired for dired-read-mail \(\\[dired-read-mail]\).
  377. The symbols 'rmail and 'vm are the only two allowed values.")
  378.  
  379. (defvar dired-verify-modtimes t
  380.   "*If non-nil dired will revert dired buffers for modified subdirectories.
  381. See also dired-no-confirm <V>.")
  382.  
  383. ;;;###autoload
  384. (defvar dired-refresh-automatically t
  385.   "*If non-nil, refresh dired buffers automatically after file operations.")
  386.  
  387. ;;; File name regular expressions and extensions.
  388.  
  389. (defvar dired-trivial-filenames "\\`\\.\\.?\\'\\|\\`#"
  390.   "*Regexp of files to skip when finding first file of a directory listing.
  391. A value of nil means move to the subdir line.
  392. A value of t means move to first file.")
  393.  
  394. (defvar dired-cleanup-alist
  395.   (list
  396.    '("tex" ".toc" ".log" ".aux" ".dvi")
  397.    '("latex" ".toc" ".log" ".aux" ".idx" ".lof" ".lot" ".glo" ".dvi")
  398.    '("bibtex" ".blg" ".bbl")
  399.    '("texinfo" ".cp" ".cps" ".fn" ".fns" ".ky" ".kys" ".pg" ".pgs"
  400.      ".tp" ".tps" ".vr" ".vrs")
  401.    '("patch" ".rej" ".orig")
  402.    '("backups" "~")
  403.    (cons "completion-ignored-extensions" completion-ignored-extensions))
  404.   "*Alist of extensions for temporary files created by various programs.
  405. Used by `dired-cleanup'.")
  406.  
  407. (defvar dired-omit-extensions
  408.   (let ((alist dired-cleanup-alist)
  409.     x result)
  410.     (while alist
  411.       (setq x (cdr (car alist))
  412.         alist (cdr alist))
  413.       (while x
  414.     (or (member (car x) result)
  415.         (setq result (cons (car x) result)))
  416.     (setq x (cdr x))))
  417.     result)
  418.   "*List of extensions for file names that will be omitted (buffer-local).
  419. This only has effect when the subdirectory is in omission mode.
  420. To make omission mode the default, set `dired-omit-files' to t.
  421. See also `dired-omit-extensions'.")
  422. (make-variable-buffer-local 'dired-omit-extensions)
  423.  
  424. (defvar dired-omit-regexps '("\\`#" "\\`\\.")
  425.   "*File names matching these regexp may be omitted (buffer-local).
  426. This only has effect when the subdirectory is in omission mode.
  427. To make omission mode the default, set `dired-omit-files' to t.
  428. This only has effect when `dired-omit-files' is t.
  429. See also `dired-omit-extensions'.")
  430. (make-variable-buffer-local 'dired-omit-regexps)
  431.  
  432. (defvar dired-filename-re-ext "\\..+\\'"  ; start from the first dot. last dot?
  433.   "*Defines what is the extension of a file name.
  434. \(match-beginning 0\) for this regexp in the file name without directory will
  435. be taken to be the start of the extension.")
  436.  
  437. ;;; Hook variables
  438.  
  439. (defvar dired-load-hook nil
  440.   "Run after loading dired.
  441. You can customize key bindings or load extensions with this.")
  442.  
  443. (defvar dired-grep-load-hook nil
  444.   "Run after loading dired-grep.")
  445.  
  446. (defvar dired-mode-hook nil
  447.   "Run at the very end of dired-mode.")
  448.  
  449. (defvar dired-before-readin-hook nil
  450.   "Hook run before a dired buffer is newly read in, created,or reverted.")
  451.  
  452. (defvar dired-after-readin-hook nil
  453.   "Hook run after each listing of a file or directory.
  454. The buffer is narrowed to the new listing.")
  455.  
  456. (defvar dired-setup-keys-hook nil
  457.   "Hook run when dired sets up its keymap.
  458. This happens the first time that `dired-mode' is called, and runs after
  459. `dired-mode-hook'.  This hook can be used to make alterations to the
  460. dired keymap.")
  461.  
  462. ;;; Internal variables
  463. ;;
  464. ;;  If you set these, know what you are doing.
  465.  
  466. ;;; Marker chars.
  467.  
  468. (defvar dired-marker-char ?*            ; the answer is 42
  469.                     ; life the universe and everything
  470.   ;; so that you can write things like
  471.   ;; (let ((dired-marker-char ?X))
  472.   ;;    ;; great code using X markers ...
  473.   ;;    )
  474.   ;; For example, commands operating on two sets of files, A and B.
  475.   ;; Or marking files with digits 0-9.  This could implicate
  476.   ;; concentric sets or an order for the marked files.
  477.   ;; The code depends on dynamic scoping on the marker char.
  478.   "In dired, character used to mark files for later commands.")
  479. (make-variable-buffer-local 'dired-marker-char)
  480.  
  481. (defconst dired-default-marker dired-marker-char)
  482. ;; Stores the default value of dired-marker-char when dynamic markers
  483. ;; are being used.
  484.  
  485. (defvar dired-del-marker ?D
  486.   "Character used to flag files for deletion.")
  487.  
  488. ;; \017=^O for Omit - other packages can chose other control characters.
  489. (defvar dired-omit-marker-char ?\017)
  490. ;; Marker used for omitted files.  Shouldn't be used by anything else.
  491.  
  492. (defvar dired-kill-marker-char ?\C-k)
  493. ;; Marker used by dired-do-kill.  Shouldn't be used by anything else.
  494.  
  495. ;;; State variables
  496.  
  497. (defvar dired-mode-line-modified "-%s%s%s-"
  498.   "*Format string to show the modification status of the buffer.")
  499.  
  500. (defvar dired-del-flags-number 0)
  501. (make-variable-buffer-local 'dired-del-flags-number)
  502. (defvar dired-marks-number 0)
  503. (make-variable-buffer-local 'dired-marks-number)
  504. (defvar dired-other-marks-number 0)
  505. (make-variable-buffer-local 'dired-other-marks-number)
  506.  
  507. (defvar dired-marked-files nil
  508.   "List of filenames from last `dired-copy-filename-as-kill' call.")
  509.  
  510. (defvar dired-directory nil
  511.   "The directory name or shell wildcard that was used as argument to `ls'.
  512. Local to each dired buffer.  May be a list, in which case the car is the
  513. directory name and the cdr is the actual files to list.")
  514. (make-variable-buffer-local 'dired-directory)
  515.  
  516. (defvar dired-internal-switches nil
  517.   "The actual (buffer-local) value of `dired-listing-switches'.
  518. The switches are represented as a list of characters.")
  519. (make-variable-buffer-local 'dired-internal-switches)
  520.  
  521. (defvar dired-subdir-alist nil
  522.   "Association list of subdirectories and their buffer positions.
  523. Each subdirectory has an element: (DIRNAME . STARTMARKER).
  524. The order of elements is the reverse of the order in the buffer.")
  525. (make-variable-buffer-local 'dired-subdir-alist)
  526.  
  527. (defvar dired-curr-subdir-min 0)
  528. ;; Cache for modeline tracking of the cursor
  529. (make-variable-buffer-local 'dired-curr-subdir-min)
  530.  
  531. (defvar dired-curr-subdir-max 0)
  532. ;; Cache for modeline tracking of the cursor
  533. (make-variable-buffer-local 'dired-curr-subdir-max)
  534.  
  535. (defvar dired-subdir-omit nil)
  536. ;; Controls whether the modeline shows Omit.
  537. (make-variable-buffer-local 'dired-subdir-omit)
  538.  
  539. (defvar dired-in-query nil)
  540. ;; let-bound to t when dired is in the process of querying the user.
  541. ;; This is to keep asynch messaging from clobbering the query prompt.
  542.  
  543. (defvar dired-overwrite-confirmed nil)
  544. ;; Fluid variable used to remember if a bunch of overwrites have been
  545. ;; confirmed.
  546.  
  547. (defvar dired-overwrite-backup-query nil)
  548. ;; Fluid var used to remember if backups have been requested for overwrites.
  549.  
  550. (defvar dired-file-creator-query nil)
  551. ;; Fluid var to remember responses to file-creator queries.
  552.  
  553. (defvar dired-omit-silent nil)
  554. ;; This is sometimes let-bound to t if messages would be annoying,
  555. ;; e.g., in dired-awrh.el. Binding to 0, only suppresses
  556. ;; \"(Nothing to omit)\" message.
  557.  
  558. (defvar dired-buffers nil
  559.   ;; Enlarged by dired-advertise
  560.   ;; Queried by function dired-buffers-for-dir. When this detects a
  561.   ;; killed buffer, it is removed from this list.
  562.   "Alist of directories and their associated dired buffers.")
  563.  
  564. (defvar dired-sort-mode nil
  565.   "Whether Dired sorts by name, date, etc. 
  566. \(buffer-local\)")
  567. ;; This is nil outside dired buffers so it can be used in the modeline
  568. (make-variable-buffer-local 'dired-sort-mode)
  569.  
  570. (defvar dired-marker-stack nil
  571.   "List of previously used dired marker characters.")
  572. (make-variable-buffer-local 'dired-marker-stack)
  573.  
  574. (defvar dired-marker-stack-pointer 0)
  575. ;; Points to the current marker in the stack
  576. (make-variable-buffer-local 'dired-marker-stack-pointer)
  577.  
  578. (defvar dired-marker-stack-cursor ?\  ; space
  579.   "Character to use as a cursor in the dired marker stack.")
  580.  
  581. (defconst dired-marker-string ""
  582.   "String version of `dired-marker-stack'.")
  583. (make-variable-buffer-local 'dired-marker-string)
  584.  
  585. (defvar dired-modeline-tracking-cmds nil)
  586. ;; List of commands after which the modeline gets updated.
  587.  
  588. ;;; Config. variables not usually considered fair game for the user.
  589.  
  590. (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
  591.  
  592. (defvar dired-log-buffer "*Dired log*")
  593. ;; Name of buffer used to log dired messages and errors.
  594.  
  595. ;;; Assoc. lists
  596.  
  597. ;; For pop ups and user input for file marking
  598. (defvar dired-query-alist
  599.   '((?\y . y) (?\040 . y)        ; `y' or SPC means accept once
  600.     (?n . n) (?\177 . n)        ; `n' or DEL skips once
  601.     (?! . yes)                ; `!' accepts rest
  602.     (?q. no) (?\e . no)            ; `q' or ESC skips rest
  603.     ;; None of these keys quit - use C-g for that.
  604.     ))
  605.  
  606. (defvar dired-sort-type-alist
  607.   ;; alist of sort flags, and the sort type, as a symbol.
  608.   ;; Don't put ?r in here.  It's handled separately.
  609.   '((?t . date) (?S . size) (?U . unsort) (?X . ext)))
  610.  
  611. ;;; Internal regexps for examining ls listings.
  612. ;;
  613. ;; Many of these regexps must be tested at beginning-of-line, but are also
  614. ;; used to search for next matches, so neither omitting "^" nor
  615. ;; replacing "^" by "\n" (to make it slightly faster) will work.
  616.  
  617. (defvar dired-re-inode-size "[ \t0-9]*")
  618. ;; Regexp for optional initial inode and file size.
  619. ;; Must match output produced by ls' -i and -s flags.
  620.  
  621. (defvar dired-re-mark "^[^ \n\r]")
  622. ;; Regexp matching a marked line.
  623. ;; Important: the match ends just after the marker.
  624.  
  625. (defvar dired-re-maybe-mark "^. ")
  626.  
  627. (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
  628. ;; Matches directory lines
  629.  
  630. (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
  631. ;; Matches symlink lines
  632.  
  633. (defvar dired-re-exe;; match ls permission string of an executable file
  634.   (mapconcat (function
  635.           (lambda (x)
  636.         (concat dired-re-maybe-mark dired-re-inode-size x)))
  637.          '("-[-r][-w][xs][-r][-w].[-r][-w]."
  638.            "-[-r][-w].[-r][-w][xs][-r][-w]."
  639.            "-[-r][-w].[-r][-w].[-r][-w][xst]")
  640.          "\\|"))
  641.  
  642. (defvar dired-re-dot "^.* \\.\\.?/?$")    ; with -F, might end in `/'
  643. ;; . and .. files
  644.  
  645. (defvar dired-re-month-and-time
  646.   (concat
  647.    " \\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|June?\\|July?\\|Aug\\|Sep\\|Oct\\|Nov\\|"
  648.                     ; June and July are for HP-UX 9.0
  649.    "Dec\\) [ 0-3][0-9]\\("
  650.    " [012][0-9]:[0-6][0-9] \\|" ; time
  651.    "  [12][90][0-9][0-9] \\|"   ; year on IRIX, NeXT, SunOS, ULTRIX, Apollo,
  652.                     ; HP-UX, A/UX
  653.    " [12][90][0-9][0-9]  \\)"   ; year on AIX
  654.    ))
  655. ;; This regexp MUST match all the way to first character of the filename.
  656. ;; You can loosen it to taste, but then you might bomb on filenames starting
  657. ;; with a space. This will have to be modified for non-english month names.
  658.  
  659. (defvar dired-subdir-regexp
  660.   "\\([\n\r]\n\\|\\`\\). \\([^\n\r]+\\)\\(:\\)\\(\\.\\.\\.\r\\|[\n\r]\\)")
  661.   ;; Regexp matching a maybe hidden subdirectory line in ls -lR output.
  662.   ;; Subexpression 2 is the subdirectory proper, no trailing colon.
  663.   ;; Subexpression 3 must end right before the \n or \r at the end of
  664.   ;; the subdir heading.  Matches headings after indentation has been done.
  665.  
  666. (defvar dired-unhandle-add-files nil)
  667. ;; List of files that the dired handler function need not add to dired buffers.
  668. ;; This is because they have already been added, most likely in
  669. ;; dired-create-files.  This is because dired-create-files add files with
  670. ;; special markers.
  671.  
  672. ;;; history variables
  673.  
  674. (defvar dired-regexp-history nil
  675.   "History list of regular expressions used in Dired commands.")
  676.  
  677. (defvar dired-chmod-history nil
  678.   "History of arguments to chmod in dired.")
  679.  
  680. (defvar dired-chown-history nil
  681.   "History of arguments to chown in dired.")
  682.  
  683. (defvar dired-chgrp-history nil
  684.   "History of arguments to chgrp in dired.")
  685.  
  686. (defvar dired-cleanup-history nil
  687.   "History of arguments to dired-cleanup.")
  688.  
  689. (defvar dired-goto-file-history nil)
  690. ;; History for dired-goto-file and dired-goto-subdir
  691. (put 'dired-goto-file-history 'cursor-end t) ; for gmhist
  692.  
  693. (defvar dired-history nil)
  694. ;; Catch-all history variable for dired file ops without
  695. ;; their own history.
  696.  
  697. (defvar dired-op-history-alist
  698.   ;; alist of dired file operations and history symbols
  699.   '((chgrp . dired-chgrp-history) (chown . dired-chown-history)
  700.     (chmod . dired-chmod-history) ))
  701.  
  702. ;;; Tell the byte-compiler that we know what we're doing.
  703. ;;; Do we?
  704.  
  705. (defvar file-name-handler-alist)
  706. (defvar inhibit-file-name-operation)
  707. (defvar inhibit-file-name-handlers)
  708. (defvar efs-dired-host-type)
  709.  
  710.  
  711. ;;;;------------------------------------------------------------------
  712. ;;;; Utilities
  713. ;;;;------------------------------------------------------------------ 
  714.  
  715. ;;; Macros
  716. ;;
  717. ;;  Macros must be defined before they are used - for the byte compiler.
  718.  
  719. (defmacro dired-get-subdir-min (elt)
  720.   ;; Returns the value of the subdir minumum for subdir with entry ELT in
  721.   ;; dired-subdir-alist.
  722.   (list 'nth 1 elt))
  723.  
  724. (defmacro dired-save-excursion (&rest body)
  725.   ;; Saves excursions of the point (not buffer) in dired buffers.
  726.   ;; It tries to be robust against deletion of the region about the point.
  727.   ;; Note that this assumes only dired-style deletions.
  728.   (let ((temp-bolm (make-symbol "bolm"))
  729.     (temp-fnlp (make-symbol "fnlp"))
  730.     (temp-offset-bol (make-symbol "offset-bol")))
  731.     (` (let (((, temp-bolm) (make-marker))
  732.          (, temp-fnlp) (, temp-offset-bol))
  733.      (let ((bol (save-excursion (skip-chars-backward "^\n\r") (point))))
  734.        (set-marker (, temp-bolm) bol)
  735.        (setq (, temp-offset-bol) (- (point) bol)
  736.          (, temp-fnlp) (memq (char-after bol) '(?\n\ ?\r))))
  737.      (unwind-protect
  738.          (progn
  739.            (,@ body))
  740.        ;; Use the marker to try to find the right line, then move to
  741.        ;; the proper column.
  742.        (goto-char (, temp-bolm))
  743.        (and (not (, temp-fnlp))
  744.         (memq (char-after (point)) '(?\n ?\r))
  745.         ;; The line containing the point got deleted. Note that this
  746.         ;; logic only works if we don't delete null lines, but we never
  747.         ;; do.
  748.         (forward-line 1)) ; don't move into a hidden line.
  749.        (skip-chars-forward "^\n\r" (+ (point) (, temp-offset-bol))))))))
  750.  
  751. (put 'dired-save-excursion 'lisp-indent-hook 0)
  752.  
  753. (defun dired-substitute-marker (pos old new)
  754.   ;; Change marker, re-fontify
  755.   (subst-char-in-region pos (1+ pos) old new)
  756.   (dired-move-to-filename))
  757.  
  758. (defmacro dired-mark-if (predicate msg)
  759.   ;; Mark all files for which CONDITION evals to non-nil.
  760.   ;; CONDITION is evaluated on each line, with point at beginning of line.
  761.   ;; MSG is a noun phrase for the type of files being marked.
  762.   ;; It should end with a noun that can be pluralized by adding `s'.
  763.   ;; Return value is the number of files marked, or nil if none were marked.
  764.   (let ((temp-pt (make-symbol "pt"))
  765.     (temp-count (make-symbol "count"))
  766.     (temp-msg (make-symbol "msg")))
  767.     (` (let (((, temp-msg) (, msg))
  768.          ((, temp-count) 0)
  769.          (, temp-pt) buffer-read-only)
  770.      (save-excursion
  771.        (if (, temp-msg) (message "Marking %ss..." (, temp-msg)))
  772.        (goto-char (point-min))
  773.        (while (not (eobp))
  774.          (if (and (, predicate)
  775.               (not (char-equal (following-char) dired-marker-char)))
  776.          (progn
  777.            ;; Doing this rather than delete-char, insert
  778.            ;; avoids re-computing markers
  779.            (setq (, temp-pt) (point))
  780.            (dired-substitute-marker
  781.             (, temp-pt)
  782.             (following-char) dired-marker-char)
  783.            (setq (, temp-count) (1+ (, temp-count)))))
  784.          (forward-line 1))
  785.        (if (, temp-msg)
  786.            (message "%s %s%s %s%s."
  787.             (, temp-count)
  788.             (, temp-msg)
  789.             (dired-plural-s (, temp-count))
  790.             (if (eq dired-marker-char ?\040) "un" "")
  791.             (if (eq dired-marker-char dired-del-marker)
  792.                 "flagged" "marked"))))
  793.      (and (> (, temp-count) 0) (, temp-count))))))
  794.  
  795. (defmacro dired-map-over-marks (body arg &optional show-progress)
  796. ;;  Perform BODY with point somewhere on each marked line
  797. ;;  and return a list of BODY's results.
  798. ;;  If no marked file could be found, execute BODY on the current line.
  799. ;;  If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
  800. ;;  files instead of the marked files.
  801. ;;  If ARG is t, only apply to marked files.  If there are no marked files,
  802. ;;  the result is a noop.
  803. ;;  If ARG is otherwise non-nil, use current file instead.
  804. ;;  If optional third arg SHOW-PROGRESS evaluates to non-nil,
  805. ;;  redisplay the dired buffer after each file is processed.
  806. ;;  No guarantee is made about the position on the marked line.
  807. ;;  BODY must ensure this itself if it depends on this.
  808. ;;  Search starts at the beginning of the buffer, thus the car of the list
  809. ;;  corresponds to the line nearest to the buffer's bottom.  This
  810. ;;  is also true for (positive and negative) integer values of ARG.
  811. ;;  To avoid code explosion, BODY should not be too long as it is
  812. ;;  expanded four times.
  813. ;;
  814. ;;  Warning: BODY must not add new lines before point - this may cause an
  815. ;;  endless loop.
  816. ;;  This warning should not apply any longer, sk  2-Sep-1991 14:10.
  817.   (let ((temp-found (make-symbol "found"))
  818.     (temp-results (make-symbol "results"))
  819.     (temp-regexp (make-symbol "regexp"))
  820.     (temp-curr-pt (make-symbol "curr-pt"))
  821.     (temp-next-position (make-symbol "next-position")))
  822.     (` (let (buffer-read-only case-fold-search (, temp-found) (, temp-results))
  823.      (dired-save-excursion
  824.        (if (and (, arg) (not (eq (, arg) t)))
  825.            (if (integerp (, arg))
  826.            (and (not (zerop (, arg)))
  827.             (progn;; no save-excursion, want to move point.
  828.               (dired-repeat-over-lines
  829.                arg
  830.                (function (lambda ()
  831.                        (if (, show-progress) (sit-for 0))
  832.                        (setq (, temp-results)
  833.                          (cons (, body)
  834.                            (, temp-results))))))
  835.               (if (<  (, arg) 0)
  836.                   (nreverse (, temp-results))
  837.                 (, temp-results))))
  838.          ;; non-nil, non-integer ARG means use current file:
  839.          (list (, body)))
  840.          (let (((, temp-regexp)
  841.             (concat "^" (regexp-quote (char-to-string
  842.                            dired-marker-char))))
  843.            (, temp-curr-pt) (, temp-next-position))
  844.            (save-excursion
  845.          (goto-char (point-min))
  846.          ;; remember position of next marked file before BODY
  847.          ;; can insert lines before the just found file,
  848.          ;; confusing us by finding the same marked file again
  849.          ;; and again and...
  850.          (setq (, temp-next-position)
  851.                (and (re-search-forward (, temp-regexp) nil t)
  852.                 (point-marker))
  853.                (, temp-found) (not (null (, temp-next-position))))
  854.          (while (, temp-next-position)
  855.            (setq (, temp-curr-pt) (goto-char (, temp-next-position))
  856.              ;; need to get next position BEFORE body
  857.              (, temp-next-position)
  858.              (and (re-search-forward (, temp-regexp) nil t)
  859.                   (point-marker)))
  860.            (goto-char (, temp-curr-pt))
  861.            (if (, show-progress) (sit-for 0))
  862.            (setq (, temp-results) (cons (, body) (, temp-results)))))
  863.            (if (, temp-found)
  864.            (, temp-results)
  865.          ;; Do current file, unless arg is t
  866.          (and (not (eq (, arg) t))
  867.               (list (, body)))))))))))
  868.  
  869. ;;; General utility functions
  870.  
  871. (defun dired-buffer-more-recently-used-p (buffer1 buffer2)
  872.   "Return t if BUFFER1 is more recently used than BUFFER2."
  873.   (if (equal buffer1 buffer2)
  874.       nil
  875.     (let ((more-recent nil)
  876.       (list (buffer-list)))
  877.       (while (and list
  878.           (not (setq more-recent (equal buffer1 (car list))))
  879.           (not (equal buffer2 (car list))))
  880.     (setq list (cdr list)))
  881.       more-recent)))
  882.  
  883. (defun dired-file-modtime (file)
  884.   ;; Return the modtime of FILE, which is assumed to be already expanded
  885.   ;; by expand-file-name.
  886.   (let ((handler (find-file-name-handler file 'dired-file-modtime)))
  887.     (if handler
  888.     (funcall handler 'dired-file-modtime file)
  889.       (nth 5 (file-attributes file)))))
  890.  
  891. (defun dired-set-file-modtime (file alist)
  892.   ;; Set the modtime for FILE in the subdir alist ALIST.
  893.   (let ((handler (find-file-name-handler file 'dired-set-file-modtime)))
  894.     (if handler
  895.     (funcall handler 'dired-set-file-modtime file alist)
  896.       (let ((elt (assoc file alist)))
  897.     (if elt
  898.         (setcar (nthcdr 4 elt) (nth 5 (file-attributes file))))))))
  899.  
  900. (defun dired-map-over-marks-check (fun arg op-symbol operation
  901.                        &optional show-progress no-confirm)
  902.   ;; Map FUN over marked files (with second ARG like in dired-map-over-marks)
  903.   ;; and display failures.
  904.  
  905.   ;; FUN takes zero args.  It returns non-nil (the offending object, e.g.
  906.   ;; the short form of the filename) for a failure and probably logs a
  907.   ;; detailed error explanation using function `dired-log'.
  908.  
  909.   ;; OP-SYMBOL is s symbol representing the operation.
  910.   ;; eg. 'compress
  911.  
  912.   ;; OPERATION is a string describing the operation performed (e.g.
  913.   ;; "Compress").  It is used with `dired-mark-pop-up' to prompt the user
  914.   ;; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
  915.   ;; `Failed to compress 1 of 2 files - type y to see why ("foo")')
  916.  
  917.   ;; SHOW-PROGRESS if non-nil means redisplay dired after each file.
  918.  
  919.   (if (or no-confirm (dired-mark-confirm op-symbol operation arg))
  920.       (let* ((total-list;; all of FUN's return values
  921.           (dired-map-over-marks (funcall fun) arg show-progress))
  922.          (total (length total-list))
  923.          (failures (delq nil total-list))
  924.          (count (length failures)))
  925.     (if (not failures)
  926.         (message "%s: %d file%s." operation total (dired-plural-s total))
  927.       (message "Failed to %s %d of %d file%s - type y to see why %s"
  928.            operation count total (dired-plural-s total)
  929.            ;; this gives a short list of failed files in parens
  930.            ;; which may be sufficient for the user even
  931.            ;; without typing `W' for the process' diagnostics
  932.            failures)
  933.       ;; end this bunch of errors:
  934.       (dired-log-summary
  935.        (buffer-name (current-buffer))
  936.        (format
  937.         "Failed to %s %d of %d file%s"
  938.         operation count total (dired-plural-s total))
  939.        failures)))))
  940.  
  941. (defun dired-make-switches-string (list)
  942. ;; Converts a list of cracters to a string suitable for passing to ls.
  943.   (concat "-" (mapconcat 'char-to-string list "")))
  944.  
  945. (defun dired-make-switches-list (string)
  946. ;; Converts a string of ls switches to a list of characters.
  947.   (delq ?- (mapcar 'identity string)))
  948.  
  949. ;; Cloning replace-match to work on strings instead of in buffer:
  950. ;; The FIXEDCASE parameter of replace-match is not implemented.
  951. (defun dired-string-replace-match (regexp string newtext
  952.                       &optional literal global)
  953.   ;; Replace first match of REGEXP in STRING with NEWTEXT.
  954.   ;; If it does not match, nil is returned instead of the new string.
  955.   ;; Optional arg LITERAL means to take NEWTEXT literally.
  956.   ;; Optional arg GLOBAL means to replace all matches.
  957.   (if global
  958.         (let ((result "") (start 0) mb me)
  959.       (while (string-match regexp string start)
  960.         (setq mb (match-beginning 0)
  961.           me (match-end 0)
  962.           result (concat result
  963.                  (substring string start mb)
  964.                  (if literal
  965.                      newtext
  966.                    (dired-expand-newtext string newtext)))
  967.           start me))
  968.       (if mb            ; matched at least once
  969.           (concat result (substring string start))
  970.         nil))
  971.     ;; not GLOBAL
  972.     (if (not (string-match regexp string 0))
  973.     nil
  974.       (concat (substring string 0 (match-beginning 0))
  975.           (if literal newtext (dired-expand-newtext string newtext))
  976.           (substring string (match-end 0))))))
  977.  
  978. (defun dired-expand-newtext (string newtext)
  979.   ;; Expand \& and \1..\9 (referring to STRING) in NEWTEXT, using match data.
  980.   ;; Note that in Emacs 18 match data are clipped to current buffer
  981.   ;; size...so the buffer should better not be smaller than STRING.
  982.   (let ((pos 0)
  983.     (len (length newtext))
  984.     (expanded-newtext ""))
  985.     (while (< pos len)
  986.       (setq expanded-newtext
  987.         (concat expanded-newtext
  988.             (let ((c (aref newtext pos)))
  989.               (if (= ?\\ c)
  990.               (cond ((= ?\& (setq c
  991.                           (aref newtext
  992.                             (setq pos (1+ pos)))))
  993.                  (substring string
  994.                         (match-beginning 0)
  995.                         (match-end 0)))
  996.                 ((and (>= c ?1) (<= c ?9))
  997.                  ;; return empty string if N'th
  998.                  ;; sub-regexp did not match:
  999.                  (let ((n (- c ?0)))
  1000.                    (if (match-beginning n)
  1001.                        (substring string
  1002.                           (match-beginning n)
  1003.                           (match-end n))
  1004.                      "")))
  1005.                 (t
  1006.                  (char-to-string c)))
  1007.             (char-to-string c)))))
  1008.       (setq pos (1+ pos)))
  1009.     expanded-newtext))
  1010.  
  1011. (defun dired-in-this-tree (file dir)
  1012.   ;;Is FILE part of the directory tree starting at DIR?
  1013.   (let ((len (length dir)))
  1014.     (and (>= (length file) len)
  1015.      (string-equal (substring file 0 len) dir))))
  1016.  
  1017. (defun dired-tree-lessp (dir1 dir2)
  1018.   ;; Lexicographic order on pathname components, like `ls -lR':
  1019.   ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
  1020.   ;;   i.e., iff DIR1 is a (grand)parent dir of DIR2,
  1021.   ;;   or DIR1 and DIR2 are in the same parentdir and their last
  1022.   ;;   components are string-lessp.
  1023.   ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
  1024.   ;; string-lessp could arguably be replaced by file-newer-than-file-p
  1025.   ;;   if dired-internal-switches contained `t'.
  1026.   (let ((dir1 (file-name-as-directory dir1))
  1027.     (dir2 (file-name-as-directory dir2))
  1028.     (start1 1)
  1029.     (start2 1)
  1030.     comp1 comp2 end1 end2)
  1031.     (while (progn
  1032.          (setq end1 (string-match "/" dir1 start1)
  1033.            comp1 (substring dir1 start1 end1)
  1034.            end2 (string-match "/" dir2 start2)
  1035.            comp2 (substring dir2 start2 end2))
  1036.            (and end1 end2 (string-equal comp1 comp2)))
  1037.       (setq start1 (1+ end1)
  1038.         start2 (1+ end2)))
  1039.     (if (eq (null end1) (null end2))
  1040.     (string-lessp comp1 comp2)
  1041.       (null end1))))
  1042.  
  1043. ;; So that we can support case-insensitive systems.
  1044. (fset 'dired-file-name-lessp 'string-lessp)
  1045.  
  1046.  
  1047. ;;;; ------------------------------------------------------------------
  1048. ;;;; Initializing Dired
  1049. ;;;; ------------------------------------------------------------------
  1050.  
  1051. ;;; Set the minor mode alist
  1052.  
  1053. (or (equal (assq 'dired-sort-mode minor-mode-alist)
  1054.        '(dired-sort-mode dired-sort-mode))
  1055.     ;; Test whether this has already been done in case dired is reloaded
  1056.     ;; There may be several elements with dired-sort-mode as car.
  1057.     (setq minor-mode-alist
  1058.       ;; cons " Omit" in first, so that it doesn't
  1059.       ;; get stuck between the directory and sort mode on the
  1060.       ;; mode line.
  1061.       (cons '(dired-sort-mode dired-sort-mode)
  1062.         (cons '(dired-subdir-omit " Omit")
  1063.               (cons '(dired-marker-stack dired-marker-string)
  1064.                 minor-mode-alist)))))
  1065.  
  1066. ;;; Keymaps
  1067.  
  1068. (defvar dired-mode-map nil
  1069.   "Local keymap for dired-mode buffers.")
  1070. (defvar dired-regexp-map nil
  1071.   "Dired keymap for commands that use regular expressions.")
  1072. (defvar dired-diff-map nil
  1073.   "Dired keymap for diff and related commands.")
  1074. (defvar dired-subdir-map nil
  1075.   "Dired keymap for commands that act on subdirs, or the files within them.")
  1076.  
  1077. (defvar dired-keymap-grokked nil
  1078.   "Set to t after dired has grokked the global keymap.")
  1079.  
  1080. (defun dired-key-description (cmd &rest prefixes)
  1081.   ;; Return a key description string for a menu.  If prefixes are given,
  1082.   ;; they should be either strings, integers, or 'universal-argument.
  1083.   (let ((key (where-is-internal cmd dired-mode-map t)))
  1084.     (if key
  1085.     (key-description
  1086.      (apply 'vconcat
  1087.         (append
  1088.          (mapcar
  1089.           (function
  1090.            (lambda (x)
  1091.              (cond ((eq x 'universal-argument)
  1092.                 (where-is-internal 'universal-argument
  1093.                            dired-mode-map t))
  1094.                ((integerp x) (int-to-string x))
  1095.                (t x))))
  1096.           prefixes)
  1097.          (list key))))
  1098.       "")))
  1099.  
  1100. (defun dired-grok-keys (to-command from-command)
  1101.   ;; Assigns to TO-COMMAND the keys for the global binding of FROM-COMMAND.
  1102.   ;; Does not clobber anything in the local keymap.  In emacs 19 should
  1103.   ;; use substitute-key-definition, but I believe that this will
  1104.   ;; clobber things in the local map.
  1105.   (let ((keys (where-is-internal from-command)))
  1106.     (while keys
  1107.       (condition-case nil
  1108.       (if (eq (global-key-binding (car keys)) (key-binding (car keys)))
  1109.           (local-set-key (car keys) to-command))
  1110.     (error nil))
  1111.       (setq keys (cdr keys)))))
  1112.  
  1113. (defun dired-grok-keymap ()
  1114.   ;; Initialize the dired keymaps.
  1115.   ;; This is actually done the first time that dired-mode runs.
  1116.   ;; We do it this late, to be sure that the user's global-keymap has
  1117.   ;; stabilized.
  1118.   (if dired-keymap-grokked
  1119.       () ; we've done it
  1120.     ;; Watch out for dired being invoked from the command line.
  1121.     ;; This is a bit kludgy, but so is the emacs startup sequence IMHO.
  1122.     (if (and term-setup-hook (boundp 'command-line-args-left))
  1123.     (progn
  1124.       (if (string-equal "18." (substring emacs-version 0 3))
  1125.           (funcall term-setup-hook)
  1126.         (run-hooks 'term-setup-hook))
  1127.       (setq term-setup-hook nil)))
  1128.     (setq dired-keymap-grokked t)
  1129.     (run-hooks 'dired-setup-keys-hook)
  1130.     (dired-grok-keys 'dired-next-line 'next-line)
  1131.     (dired-grok-keys 'dired-previous-line 'previous-line)
  1132.     (dired-grok-keys 'dired-undo 'undo)
  1133.     (dired-grok-keys 'dired-undo 'advertised-undo)
  1134.     (dired-grok-keys 'dired-scroll-up 'scroll-up)
  1135.     (dired-grok-keys 'dired-scroll-down 'scroll-down)
  1136.     (dired-grok-keys 'dired-beginning-of-buffer 'beginning-of-buffer)
  1137.     (dired-grok-keys 'dired-end-of-buffer 'end-of-buffer)
  1138.     (dired-grok-keys 'dired-next-subdir 'forward-paragraph)
  1139.     (dired-grok-keys 'dired-prev-subdir 'backward-paragraph)))
  1140.  
  1141. ;; The regexp-map is used for commands using regexp's.
  1142. (if dired-regexp-map
  1143.     ()
  1144.   (setq dired-regexp-map (make-sparse-keymap))
  1145.   (define-key dired-regexp-map "C" 'dired-do-copy-regexp)
  1146.   ;; Not really a regexp, but does transform file names.
  1147.   (define-key dired-regexp-map "D" 'dired-downcase)
  1148.   (define-key dired-regexp-map "H" 'dired-do-hardlink-regexp)
  1149.   (define-key dired-regexp-map "R" 'dired-do-rename-regexp)
  1150.   (define-key dired-regexp-map "S" 'dired-do-symlink-regexp)
  1151.   (define-key dired-regexp-map "U" 'dired-upcase)
  1152.   (define-key dired-regexp-map "Y" 'dired-do-relsymlink-regexp)
  1153.   (define-key dired-regexp-map "c" 'dired-cleanup)
  1154.   (define-key dired-regexp-map "d" 'dired-flag-files-regexp)
  1155.   (define-key dired-regexp-map "e" 'dired-mark-extension)
  1156.   (define-key dired-regexp-map "m" 'dired-mark-files-regexp)
  1157.   (define-key dired-regexp-map "o" 'dired-add-omit-regexp)
  1158.   (define-key dired-regexp-map "x" 'dired-flag-extension)) ; a string, rather
  1159.                     ; than a regexp.
  1160.  
  1161. (if dired-diff-map
  1162.     ()
  1163.   (setq dired-diff-map (make-sparse-keymap))
  1164.   (define-key dired-diff-map "d" 'dired-diff)
  1165.   (define-key dired-diff-map "b" 'dired-backup-diff)
  1166.   (define-key dired-diff-map "m" 'dired-emerge)
  1167.   (define-key dired-diff-map "a" 'dired-emerge-with-ancestor)
  1168.   (define-key dired-diff-map "e" 'dired-ediff)
  1169.   (define-key dired-diff-map "p" 'dired-epatch))
  1170.  
  1171. (if dired-subdir-map
  1172.     ()
  1173.   (setq dired-subdir-map (make-sparse-keymap))
  1174.   (define-key dired-subdir-map "n" 'dired-redisplay-subdir)
  1175.   (define-key dired-subdir-map "m" 'dired-mark-subdir-files)
  1176.   (define-key dired-subdir-map "d" 'dired-flag-subdir-files)
  1177.   (define-key dired-subdir-map "z" 'dired-compress-subdir-files))
  1178.  
  1179. (fset 'dired-regexp-prefix dired-regexp-map)
  1180. (fset 'dired-diff-prefix dired-diff-map)
  1181. (fset 'dired-subdir-prefix dired-subdir-map)
  1182. (fset 'efs-dired-prefix (function (lambda ()
  1183.                     (interactive)
  1184.                     (error "efs-dired not loaded yet"))))
  1185.  
  1186. ;; the main map
  1187. (if dired-mode-map
  1188.     nil
  1189.   ;; Force `f' rather than `e' in the mode doc:
  1190.   (fset 'dired-advertised-find-file 'dired-find-file)
  1191.   (fset 'dired-advertised-next-subdir 'dired-next-subdir)
  1192.   (fset 'dired-advertised-prev-subdir 'dired-prev-subdir)
  1193.   (setq dired-mode-map (make-keymap))
  1194.   (suppress-keymap dired-mode-map)
  1195.   ;; Commands to mark certain categories of files
  1196.   (define-key dired-mode-map "~" 'dired-flag-backup-files)
  1197.   (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
  1198.   (define-key dired-mode-map "*" 'dired-mark-executables)
  1199.   (define-key dired-mode-map "." 'dired-clean-directory)
  1200.   (define-key dired-mode-map "/" 'dired-mark-directories)
  1201.   (define-key dired-mode-map "@" 'dired-mark-symlinks)
  1202.   (define-key dired-mode-map "," 'dired-mark-rcs-files)
  1203.   (define-key dired-mode-map "\M-(" 'dired-mark-sexp)
  1204.   (define-key dired-mode-map "\M-d" 'dired-mark-files-from-other-dired-buffer)
  1205.   (define-key dired-mode-map "\M-c" 'dired-mark-files-compilation-buffer)
  1206.   ;; Upper case keys (except ! and &) for operating on the marked files
  1207.   (define-key dired-mode-map "A" 'dired-do-tags-search)
  1208.   (define-key dired-mode-map "B" 'dired-do-byte-compile)
  1209.   (define-key dired-mode-map "C" 'dired-do-copy)
  1210.   (define-key dired-mode-map "E" 'dired-do-grep)
  1211.   (define-key dired-mode-map "F" 'dired-do-find-file)
  1212.   (define-key dired-mode-map "G" 'dired-do-chgrp)
  1213.   (define-key dired-mode-map "H" 'dired-do-hardlink)
  1214.   (define-key dired-mode-map "I" 'dired-do-insert-subdir)
  1215.   (define-key dired-mode-map "K" 'dired-do-kill-file-lines)
  1216.   (define-key dired-mode-map "L" 'dired-do-load)
  1217.   (define-key dired-mode-map "M" 'dired-do-chmod)
  1218.   (define-key dired-mode-map "N" 'dired-do-redisplay)
  1219.   (define-key dired-mode-map "O" 'dired-do-chown)
  1220.   (define-key dired-mode-map "P" 'dired-do-print)
  1221.   (define-key dired-mode-map "Q" 'dired-do-tags-query-replace)
  1222.   (define-key dired-mode-map "R" 'dired-do-rename)
  1223.   (define-key dired-mode-map "S" 'dired-do-symlink)
  1224.   (define-key dired-mode-map "T" 'dired-do-total-size)
  1225.   (define-key dired-mode-map "U" 'dired-do-uucode)
  1226.   (define-key dired-mode-map "W" 'dired-copy-filenames-as-kill)
  1227.   (define-key dired-mode-map "X" 'dired-do-delete)
  1228.   (define-key dired-mode-map "Y" 'dired-do-relsymlink)
  1229.   (define-key dired-mode-map "Z" 'dired-do-compress)
  1230.   (define-key dired-mode-map "!" 'dired-do-shell-command)
  1231.   (define-key dired-mode-map "&" 'dired-do-background-shell-command)
  1232.   ;; Make all regexp commands share a `%' prefix:
  1233.   (define-key dired-mode-map "%" 'dired-regexp-prefix)
  1234.   ;; Lower keys for commands not operating on all the marked files
  1235.   (define-key dired-mode-map "a" 'dired-apropos)
  1236.   (define-key dired-mode-map "c" 'dired-change-marks)
  1237.   (define-key dired-mode-map "d" 'dired-flag-file-deletion)
  1238.   (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion-backup)
  1239.   (define-key dired-mode-map "e" 'dired-find-file)
  1240.   (define-key dired-mode-map "f" 'dired-advertised-find-file)
  1241.   (define-key dired-mode-map "g" 'revert-buffer)
  1242.   (define-key dired-mode-map "h" 'dired-describe-mode)
  1243.   (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
  1244.   (define-key dired-mode-map "k" 'dired-kill-subdir)
  1245.   (define-key dired-mode-map "m" 'dired-mark)
  1246.   (define-key dired-mode-map "o" 'dired-find-file-other-window)
  1247.   (define-key dired-mode-map "q" 'dired-quit)
  1248.   (define-key dired-mode-map "r" 'dired-read-mail)
  1249.   (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
  1250.   (define-key dired-mode-map "t" 'dired-get-target-directory)
  1251.   (define-key dired-mode-map "u" 'dired-unmark)
  1252.   (define-key dired-mode-map "v" 'dired-view-file)
  1253.   (define-key dired-mode-map "w" (if (fboundp 'find-file-other-frame)
  1254.                      'dired-find-file-other-frame
  1255.                    'dired-find-file-other-window))
  1256.   (define-key dired-mode-map "x" 'dired-expunge-deletions)
  1257.   (define-key dired-mode-map "y" 'dired-why)
  1258.   (define-key dired-mode-map "+" 'dired-create-directory)
  1259.   (define-key dired-mode-map "`" 'dired-recover-file)
  1260.   ;; dired-jump-back Should be in the global map, but put them here
  1261.   ;; too anyway.
  1262.   (define-key dired-mode-map "\C-x\C-j" 'dired-jump-back)
  1263.   (define-key dired-mode-map "\C-x4\C-j" 'dired-jump-back-other-window)
  1264.   (define-key dired-mode-map "\C-x5\C-j" 'dired-jump-back-other-frame)
  1265.   ;; Comparison commands
  1266.   (define-key dired-mode-map "=" 'dired-diff-prefix)
  1267.   ;; moving
  1268.   (define-key dired-mode-map "<" 'dired-prev-dirline)
  1269.   (define-key dired-mode-map ">" 'dired-next-dirline)
  1270.   (define-key dired-mode-map " "  'dired-next-line)
  1271.   (define-key dired-mode-map "n" 'dired-next-line)
  1272.   (define-key dired-mode-map "\C-n" 'dired-next-line)
  1273.   (define-key dired-mode-map "p" 'dired-previous-line)
  1274.   (define-key dired-mode-map "\C-p" 'dired-previous-line)
  1275.   (define-key dired-mode-map "\C-v" 'dired-scroll-up)
  1276.   (define-key dired-mode-map "\M-v" 'dired-scroll-down)
  1277.   (define-key dired-mode-map "\M-<" 'dired-beginning-of-buffer)
  1278.   (define-key dired-mode-map "\M->" 'dired-end-of-buffer)
  1279.   (define-key dired-mode-map "\C-m" 'dired-advertised-find-file)
  1280.   ;; motion by subdirectories
  1281.   (define-key dired-mode-map "^" 'dired-up-directory)
  1282.   (define-key dired-mode-map "\M-\C-u" 'dired-up-directory)
  1283.   (define-key dired-mode-map "\M-\C-d" 'dired-down-directory)
  1284.   (define-key dired-mode-map "\M-\C-n" 'dired-advertised-next-subdir)
  1285.   (define-key dired-mode-map "\M-\C-p" 'dired-advertised-prev-subdir)
  1286.   (define-key dired-mode-map "\C-j" 'dired-goto-subdir)
  1287.   ;; move to marked files
  1288.   (define-key dired-mode-map "\M-p" 'dired-prev-marked-file)
  1289.   (define-key dired-mode-map "\M-n" 'dired-next-marked-file)
  1290.   ;; hiding
  1291.   (define-key dired-mode-map "$" 'dired-hide-subdir)
  1292.   (define-key dired-mode-map "\M-$" 'dired-hide-all)
  1293.   ;; omitting
  1294.   (define-key dired-mode-map "\C-o" 'dired-omit-toggle)
  1295.   ;; markers
  1296.   (define-key dired-mode-map "\(" 'dired-set-marker-char)
  1297.   (define-key dired-mode-map "\)" 'dired-restore-marker-char)
  1298.   (define-key dired-mode-map "'" 'dired-marker-stack-left)
  1299.   (define-key dired-mode-map "\\" 'dired-marker-stack-right)
  1300.   ;; misc
  1301.   (define-key dired-mode-map "\C-i" 'dired-mark-prefix)
  1302.   (define-key dired-mode-map "?" 'dired-summary)
  1303.   (define-key dired-mode-map "\177" 'dired-backup-unflag)
  1304.   (define-key dired-mode-map "\C-_" 'dired-undo)
  1305.   (define-key dired-mode-map "\C-xu" 'dired-undo)
  1306.   (define-key dired-mode-map "\M-\C-?" 'dired-unmark-all-files)
  1307.   ;; The subdir map
  1308.   (define-key dired-mode-map "|" 'dired-subdir-prefix)
  1309.   ;; efs submap
  1310.   (define-key dired-mode-map "\M-e" 'efs-dired-prefix))
  1311.  
  1312.  
  1313.  
  1314. ;;;;------------------------------------------------------------------
  1315. ;;;; The dired command
  1316. ;;;;------------------------------------------------------------------
  1317.  
  1318. ;;; User commands:
  1319. ;;; All of these commands should have a binding in the global keymap.
  1320.  
  1321. ;;;###autoload (define-key ctl-x-map "d" 'dired)
  1322. ;;;###autoload
  1323. (defun dired (dirname &optional switches)
  1324.   "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
  1325. Optional second argument SWITCHES specifies the `ls' options used.
  1326. \(Interactively, use a prefix argument to be able to specify SWITCHES.)
  1327. Dired displays a list of files in DIRNAME (which may also have
  1328. shell wildcards appended to select certain files).  If DIRNAME is a cons,
  1329. its first element is taken as the directory name and the resr as an explicit
  1330. list of files to make directory entries for.
  1331. \\<dired-mode-map>\
  1332. You can move around in it with the usual commands.
  1333. You can flag files for deletion with \\[dired-flag-file-deletion] and then
  1334. delete them by typing \\[dired-expunge-deletions].
  1335. Type \\[dired-describe-mode] after entering dired for more info.
  1336.  
  1337. If DIRNAME is already in a dired buffer, that buffer is used without refresh."
  1338.   ;; Cannot use (interactive "D") because of wildcards.
  1339.   (interactive (dired-read-dir-and-switches ""))
  1340.   (switch-to-buffer (dired-noselect dirname switches)))
  1341.  
  1342. ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
  1343. ;;;###autoload
  1344. (defun dired-other-window (dirname &optional switches)
  1345.   "\"Edit\" directory DIRNAME.  Like `dired' but selects in another window."
  1346.   (interactive (dired-read-dir-and-switches "in other window "))
  1347.   (switch-to-buffer-other-window (dired-noselect dirname switches)))
  1348.  
  1349. ;;;###autoload (define-key ctl-x-5-map "d" 'dired-other-frame)
  1350. ;;;###autoload
  1351. (defun dired-other-frame (dirname &optional switches)
  1352.   "\"Edit\" directory DIRNAME.  Like `dired' but makes a new frame."
  1353.   (interactive (dired-read-dir-and-switches "in other frame "))
  1354.   (switch-to-buffer-other-frame (dired-noselect dirname switches)))
  1355.  
  1356. ;;;###autoload
  1357. (defun dired-noselect (dir-or-list &optional switches)
  1358.   "Like `dired' but returns the dired buffer as value, does not select it."
  1359.   (or dir-or-list (setq dir-or-list (expand-file-name default-directory)))
  1360.   ;; This loses the distinction between "/foo/*/" and "/foo/*" that
  1361.   ;; some shells make:
  1362.   (let (dirname)
  1363.     (if (consp dir-or-list)
  1364.     (setq dirname (car dir-or-list))
  1365.       (setq dirname dir-or-list))
  1366.     (setq dirname (expand-file-name (directory-file-name dirname)))
  1367.     (if (file-directory-p dirname)
  1368.     (setq dirname (file-name-as-directory dirname)))
  1369.     (if (consp dir-or-list)
  1370.     (setq dir-or-list (cons dirname (cdr dir-or-list)))
  1371.       (setq dir-or-list dirname))
  1372.     (dired-internal-noselect dir-or-list switches)))
  1373.  
  1374. ;; Adapted from code by wurgler@zippysun.math.uakron.edu (Tom Wurgler).
  1375. ;;;###autoload (define-key ctl-x-map "\C-j" 'dired-jump-back)
  1376. ;;;###autoload
  1377. (defun dired-jump-back ()
  1378.   "Jump back to dired.
  1379. If in a file, dired the current directory and move to file's line.
  1380. If in dired already, pop up a level and goto old directory's line.
  1381. In case the proper dired file line cannot be found, refresh the dired
  1382.   buffer and try again."
  1383.   (interactive)
  1384.   (let* ((file (if (eq major-mode 'dired-mode)
  1385.            (directory-file-name (dired-current-directory))
  1386.          buffer-file-name))
  1387.      (dir (if file
  1388.           (file-name-directory file)
  1389.         default-directory)))
  1390.     (dired dir)
  1391.     (if file (dired-really-goto-file file))))
  1392.  
  1393. ;;;###autoload (define-key ctl-x-4-map "\C-j" 'dired-jump-back-other-window)
  1394. ;;;###autoload
  1395. (defun dired-jump-back-other-window ()
  1396.   "Like \\[dired-jump-back], but to other window."
  1397.   (interactive)
  1398.   (let* ((file (if (eq major-mode 'dired-mode)
  1399.            (directory-file-name (dired-current-directory))
  1400.          buffer-file-name))
  1401.      (dir (if file
  1402.           (file-name-directory file)
  1403.         default-directory)))
  1404.     (dired-other-window dir)
  1405.     (if file (dired-really-goto-file file))))
  1406.  
  1407. ;;;###autoload (define-key ctl-x-5-map "\C-j" 'dired-jump-back-other-frame)
  1408. ;;;###autoload
  1409. (defun dired-jump-back-other-frame ()
  1410.   "Like \\[dired-jump-back], but in another frame."
  1411.   (interactive)
  1412.   (let* ((file (if (eq major-mode 'dired-mode)
  1413.            (directory-file-name (dired-current-directory))
  1414.          buffer-file-name))
  1415.      (dir (if file
  1416.           (file-name-directory file)
  1417.         default-directory)))
  1418.     (dired-other-frame dir)
  1419.     (if file (dired-really-goto-file file))))
  1420.  
  1421. ;;; Dired mode
  1422.  
  1423. ;; Dired mode is suitable only for specially formatted data.
  1424. (put 'dired-mode 'mode-class 'special)
  1425.  
  1426. (defun dired-mode (&optional dirname switches)
  1427.   "\\<dired-mode-map>Dired mode is for \"editing\" directory trees.
  1428.  
  1429. For a simple one-line help message, type \\[dired-summary]
  1430. For a moderately detailed description of dired mode, type \\[dired-describe-mode]
  1431. For the full dired info tree, type \\[universal-argument] \\[dired-describe-mode]"
  1432.   ;; Not to be called interactively (e.g. dired-directory will be set
  1433.   ;; to default-directory, which is wrong with wildcards).
  1434.   (kill-all-local-variables)
  1435.   (use-local-map dired-mode-map)
  1436.   (setq major-mode 'dired-mode
  1437.     mode-name "Dired"
  1438.     case-fold-search nil
  1439.     buffer-read-only t
  1440.     selective-display t        ; for subdirectory hiding
  1441.     selective-display-ellipses nil  ; for omit toggling
  1442.     mode-line-buffer-identification '("Dired: %12b")
  1443.     mode-line-modified (format dired-mode-line-modified "--" "--" "-")
  1444.     dired-directory (expand-file-name (or dirname default-directory))
  1445.     dired-internal-switches (dired-make-switches-list
  1446.                    (or switches dired-listing-switches)))
  1447.   (dired-advertise)            ; default-directory is already set
  1448.   (set (make-local-variable 'revert-buffer-function)
  1449.        (function dired-revert))
  1450.   (set (make-local-variable 'default-directory-function)
  1451.        'dired-current-directory)
  1452.   (set (make-local-variable 'page-delimiter)
  1453.        "\n\n")
  1454.   (set (make-local-variable 'list-buffers-directory)
  1455.        dired-directory)
  1456.   ;; Will only do something in Emacs 19.
  1457.   (add-hook (make-local-variable 'kill-buffer-hook)
  1458.         'dired-unadvertise-current-buffer)
  1459.   ;; Same here
  1460.   (if window-system
  1461.       (add-hook (make-local-variable 'post-command-hook)
  1462.         (function
  1463.          (lambda ()
  1464.            (if (memq this-command dired-modeline-tracking-cmds)
  1465.                (dired-update-mode-line t))))))
  1466.   (dired-sort-other dired-internal-switches t)
  1467.   (dired-hack-local-variables)
  1468.   (run-hooks 'dired-mode-hook)
  1469.   ;; Run this after dired-mode-hook, in case that hook makes changes to
  1470.   ;; the keymap.
  1471.   (dired-grok-keymap))
  1472.  
  1473. ;;; Internal functions for starting dired
  1474.  
  1475. (defun dired-read-dir-and-switches (str)
  1476.   ;; For use in interactive.
  1477.   (reverse (list
  1478.         (if current-prefix-arg
  1479.         (read-string "Dired listing switches: "
  1480.                  dired-listing-switches))
  1481.         (let ((default-directory (default-directory)))
  1482.           (read-file-name (format "Dired %s(directory): " str)
  1483.                   nil default-directory nil)))))
  1484.  
  1485. (defun dired-hack-local-variables ()
  1486.   "Parse, bind or evaluate any local variables for current dired buffer.
  1487. See variable `dired-local-variables-file'."
  1488.   (if (and dired-local-variables-file
  1489.        (file-exists-p dired-local-variables-file))
  1490.       (let (buffer-read-only opoint )
  1491.     (save-excursion
  1492.       (goto-char (point-max))
  1493.       (setq opoint (point-marker))
  1494.       (insert "\^L\n")
  1495.       (insert-file-contents dired-local-variables-file))
  1496.     (let ((buffer-file-name dired-local-variables-file))
  1497.       (condition-case err
  1498.           (hack-local-variables)
  1499.         (error (message "Error in dired-local-variables-file: %s" err)
  1500.            (sit-for 1))))
  1501.     ;; Must delete it as (eobp) is often used as test for last
  1502.     ;; subdir in dired.el.
  1503.     (delete-region opoint (point-max))
  1504.     (set-marker opoint nil))))
  1505.  
  1506. ;; Separate function from dired-noselect for the sake of dired-vms.el.
  1507. (defun dired-internal-noselect (dir-or-list &optional switches mode)
  1508.   ;; If there is an existing dired buffer for DIRNAME, just leave
  1509.   ;; buffer as it is (don't even call dired-revert).
  1510.   ;; This saves time especially for deep trees or with efs.
  1511.   ;; The user can type `g'easily, and it is more consistent with find-file.
  1512.   ;; But if SWITCHES are given they are probably different from the
  1513.   ;; buffer's old value, so call dired-sort-other, which does
  1514.   ;; revert the buffer.
  1515.   ;; If the user specifies a directory with emacs startup, eg.
  1516.   ;; emacs ~, dir-or-list may be unexpanded at this point.
  1517.  
  1518.   (let* ((dirname (expand-file-name (if (consp dir-or-list)
  1519.                     (car dir-or-list)
  1520.                       dir-or-list)))
  1521.      (buffer (dired-find-buffer-nocreate dir-or-list mode))
  1522.      ;; note that buffer already is in dired-mode, if found
  1523.      (new-buffer-p (not buffer))
  1524.      (old-buf (current-buffer))
  1525.      wildcard)
  1526.     (or buffer
  1527.     (let ((default-major-mode 'fundamental-mode))
  1528.       ;; We don't want default-major-mode to run hooks and set auto-fill
  1529.       ;; or whatever, now that dired-mode does not
  1530.       ;; kill-all-local-variables any longer.
  1531.       (setq buffer (create-file-buffer (directory-file-name dirname)))))
  1532.     (set-buffer buffer)
  1533.     (if (not new-buffer-p)        ; existing buffer ...
  1534.     (progn
  1535.       (if switches
  1536.           (dired-sort-other
  1537.            (if (stringp switches)
  1538.            (dired-make-switches-list switches)
  1539.          switches)))
  1540.       (if dired-verify-modtimes (dired-verify-modtimes))
  1541.       (if (and dired-find-subdir
  1542.            (not (string-equal (dired-current-directory)
  1543.                       (file-name-as-directory dirname))))
  1544.           (dired-initial-position dirname)))
  1545.       ;; Else a new buffer
  1546.       (if (file-directory-p dirname)
  1547.       (setq default-directory dirname
  1548.         wildcard (consp dir-or-list))
  1549.     (setq default-directory (file-name-directory dirname)
  1550.           wildcard t))
  1551.       (or switches (setq switches dired-listing-switches))
  1552.       (dired-mode dirname switches)
  1553.       ;; default-directory and dired-internal-switches are set now
  1554.       ;; (buffer-local), so we can call dired-readin:
  1555.       (let ((failed t))
  1556.     (unwind-protect
  1557.         (progn (dired-readin dir-or-list buffer wildcard)
  1558.            (setq failed nil))
  1559.       ;; dired-readin can fail if parent directories are inaccessible.
  1560.       ;; Don't leave an empty buffer around in that case.
  1561.       (if failed (kill-buffer buffer))))
  1562.       ;; No need to narrow since the whole buffer contains just
  1563.       ;; dired-readin's output, nothing else.  The hook can
  1564.       ;; successfully use dired functions (e.g. dired-get-filename)
  1565.       ;; as the subdir-alist has been built in dired-readin.
  1566.       (run-hooks 'dired-after-readin-hook)
  1567.       ;; I put omit-expunge after the dired-after-readin-hook
  1568.       ;; in case that hook marks files. Does this make sense? Also, users
  1569.       ;; might want to set dired-omit-files in some incredibly clever
  1570.       ;; way depending on the contents of the directory... I don't know...
  1571.       (if dired-omit-files
  1572.       (dired-omit-expunge nil t))
  1573.       (goto-char (point-min))
  1574.       (dired-initial-position dirname))
  1575.     (set-buffer old-buf)
  1576.     buffer))
  1577.  
  1578. (defun dired-find-buffer-nocreate (dir-or-list &optional mode)
  1579.   ;; Returns a dired buffer for DIR-OR-LIST. DIR-OR-LIST may be wildcard,
  1580.   ;; or a directory and alist of files.
  1581.   ;; If dired-find-subdir is non-nil, is satisfied with a dired
  1582.   ;; buffer containing DIR-OR-LIST as a subdirectory. If there is more
  1583.   ;; than one candidate, returns the most recently used.
  1584.   (if dired-find-subdir
  1585.       (let ((buffers (sort (delq (current-buffer)
  1586.                  (dired-buffers-for-dir dir-or-list t))
  1587.                (function dired-buffer-more-recently-used-p))))
  1588.     (or (car buffers)
  1589.         ;; Couldn't find another buffer. Will the current one do?
  1590.         ;; It is up dired-initial-position to actually go to the subdir.
  1591.         (and (or (equal dir-or-list dired-directory) ; covers wildcards
  1592.              (and (stringp dir-or-list)
  1593.               (not (string-equal
  1594.                 dir-or-list
  1595.                 (expand-file-name default-directory)))
  1596.               (assoc (file-name-as-directory dir-or-list)
  1597.                  dired-subdir-alist)))
  1598.          (current-buffer))))
  1599.     ;; Else just look through the buffer list.
  1600.     (let (found (blist (buffer-list)))
  1601.       (or mode (setq mode 'dired-mode))
  1602.       (save-excursion
  1603.     (while blist
  1604.       (set-buffer (car blist))
  1605.       (if (and (eq major-mode mode)
  1606.            (equal dired-directory dir-or-list))
  1607.           (setq found (car blist)
  1608.             blist nil)
  1609.         (setq blist (cdr blist)))))
  1610.       found)))
  1611.  
  1612. (defun dired-initial-position (dirname)
  1613.   ;; Where point should go in a new listing of DIRNAME.
  1614.   ;; Point assumed at beginning of new subdir line.
  1615.   (end-of-line)
  1616.   (if dired-find-subdir (dired-goto-subdir dirname))
  1617.   (if dired-trivial-filenames (dired-goto-next-nontrivial-file))
  1618.   (dired-update-mode-line t))
  1619.  
  1620. (defun dired-readin (dir-or-list buffer &optional wildcard)
  1621.   ;; Read in a new dired buffer
  1622.   ;; dired-readin differs from dired-insert-subdir in that it accepts
  1623.   ;; wildcards, erases the buffer, and builds the subdir-alist anew
  1624.   ;; (including making it buffer-local and clearing it first).
  1625.   ;; default-directory and dired-internal-switches must be buffer-local
  1626.   ;; and initialized by now.
  1627.   ;; Thus we can test (equal default-directory dirname) instead of
  1628.   ;; (file-directory-p dirname) and save a filesystem transaction.
  1629.   ;; This is wrong, if dired-before-readin-hook changes default-directory
  1630.   ;; Also, we can run this hook which may want to modify the switches
  1631.   ;; based on default-directory, e.g. with efs to a SysV host
  1632.   ;; where ls won't understand -Al switches.
  1633.   (let (dirname other-dirs)
  1634.     (if (consp dir-or-list)
  1635.     (setq dir-or-list (dired-frob-dir-list dir-or-list)
  1636.           other-dirs (cdr dir-or-list)
  1637.           dir-or-list (car dir-or-list)
  1638.           dirname (car dir-or-list))
  1639.       (setq dirname dir-or-list))
  1640.     (setq dirname (expand-file-name dirname))
  1641.     (if (consp dir-or-list)
  1642.     (setq dir-or-list (cons dirname (cdr dir-or-list))))
  1643.     (save-excursion
  1644.       (set-buffer buffer)
  1645.       (run-hooks 'dired-before-readin-hook)
  1646.       (message "Reading directory %s..." dirname)
  1647.       (let (buffer-read-only)
  1648.     (widen)
  1649.     (erase-buffer)
  1650.     (dired-readin-insert dir-or-list wildcard)
  1651.     (dired-indent-listing (point-min) (point-max-marker))
  1652.     ;; We need this to make the root dir have a header line as all
  1653.     ;; other subdirs have:
  1654.     (goto-char (point-min))
  1655.     (dired-insert-headerline (expand-file-name default-directory)))
  1656.       (message "Reading directory %s...done" dirname)
  1657.       (set-buffer-modified-p nil)
  1658.       ;; Must first make alist buffer local and set it to nil because
  1659.       ;; dired-build-subdir-alist will call dired-clear-alist first
  1660.       (setq dired-subdir-alist nil)
  1661.       (if (memq ?R dired-internal-switches)
  1662.       (dired-build-subdir-alist)
  1663.     ;; no need to parse the buffer if listing is not recursive
  1664.     (dired-simple-subdir-alist))
  1665.       (if other-dirs
  1666.       (mapcar
  1667.        (function
  1668.         (lambda (x)
  1669.           (if (dired-in-this-tree (car x) dirname)
  1670.           (dired-insert-subdir x))))
  1671.        other-dirs)))))
  1672.   
  1673. ;;; Subroutines of dired-readin
  1674.  
  1675. (defun dired-readin-insert (dir-or-list &optional wildcard)
  1676.   ;; Just insert listing for the passed-in directory or
  1677.   ;; directory-and-file list, assuming a clean buffer.
  1678.   (let* ((switches (dired-make-switches-string dired-internal-switches))
  1679.      (dir-is-list (consp dir-or-list))
  1680.      (dirname (if dir-is-list (car dir-or-list) dir-or-list)))
  1681.     (if wildcard
  1682.     (progn
  1683.       (or (file-readable-p
  1684.            (if dir-is-list
  1685.            dirname
  1686.          (directory-file-name (file-name-directory dirname))))
  1687.           (error "Directory %s inaccessible or nonexistent" dirname))
  1688.       ;; else assume it contains wildcards
  1689.       (dired-insert-directory dir-or-list switches t)
  1690.       (save-excursion
  1691.         ;; insert wildcard instead of total line:
  1692.         (goto-char (point-min))
  1693.         (if dir-is-list
  1694.         (insert "list wildcard\n")
  1695.           (insert "wildcard " (file-name-nondirectory dirname) "\n"))))
  1696.       (dired-insert-directory dir-or-list switches nil t))))
  1697.  
  1698. (defun dired-insert-directory (dir-or-list switches &optional wildcard full-p)
  1699.   ;; Do the right thing whether dir-or-list is atomic or not.  If it is,
  1700.   ;; insert all files listed in the cdr -- the car is the passed-in directory
  1701.   ;; list.
  1702.   (let ((opoint (point))
  1703.     (insert-directory-program dired-ls-program))
  1704.     (if (consp dir-or-list)
  1705.     (mapcar
  1706.      (function
  1707.       (lambda (x)
  1708.         (insert-directory x switches wildcard)))
  1709.      (cdr dir-or-list))
  1710.       (insert-directory dir-or-list switches wildcard full-p))
  1711.     (dired-insert-set-properties opoint (point)))
  1712.   (setq dired-directory dir-or-list))
  1713.  
  1714. (defun dired-frob-dir-list (dir-list)
  1715.   (let* ((top (file-name-as-directory (expand-file-name (car dir-list))))
  1716.      (tail (cdr dir-list))
  1717.      (result (list (list top)))
  1718.      elt dir)
  1719.     (setq tail
  1720.       (mapcar
  1721.        (function
  1722.         (lambda (x)
  1723.           (directory-file-name (expand-file-name x top))))
  1724.        tail))
  1725.     (while tail
  1726.       (setq dir (file-name-directory (car tail)))
  1727.       (if (setq elt (assoc dir result))
  1728.       (nconc elt (list (car tail)))
  1729.     (nconc result (list (list dir (car tail)))))
  1730.       (setq tail (cdr tail)))
  1731.     result))
  1732.  
  1733. (defun dired-insert-headerline (dir);; also used by dired-insert-subdir
  1734.   ;; Insert DIR's headerline with no trailing slash, exactly like ls
  1735.   ;; would, and put cursor where dired-build-subdir-alist puts subdir
  1736.   ;; boundaries.
  1737.   (save-excursion (insert "  " (directory-file-name dir) ":\n")))
  1738.  
  1739. (defun dired-verify-modtimes ()
  1740.   ;; Check the modtimes of all subdirs.
  1741.   (let ((alist dired-subdir-alist)
  1742.     on-disk in-mem badies)
  1743.     (while alist
  1744.       (and (setq in-mem (nth 4 (car alist)))
  1745.        (setq on-disk (dired-file-modtime (car (car alist))))
  1746.        (not (equal in-mem on-disk))
  1747.        (setq badies (cons (cons (car (car alist))
  1748.                     (nth 3 (car alist)))
  1749.                   badies)))
  1750.       (setq alist (cdr alist)))
  1751.     (and badies
  1752.      (let* ((ofile (dired-get-filename nil t))
  1753.         (osub (and (null ofile) (dired-get-subdir)))
  1754.         (opoint (point))
  1755.         (ocol (current-column)))
  1756.        (unwind-protect
  1757.            (and
  1758.         (or (memq 'revert-subdirs dired-no-confirm)
  1759.             (save-window-excursion
  1760.               (let ((flist (mapcar
  1761.                     (function
  1762.                      (lambda (f)
  1763.                        (dired-abbreviate-file-name (car f))))
  1764.                     badies)))
  1765.             (switch-to-buffer (current-buffer))
  1766.                (dired-mark-pop-up
  1767.             "*Stale Subdirectories*" 'revert-subdirs
  1768.             flist 'y-or-n-p
  1769.             (if (= (length flist) 1)
  1770.                 (concat "Subdirectory " (car flist)
  1771.                     " has changed on disk.  Re-list? ")
  1772.               "Subdirectories have changed on disk.  Re-list? "))
  1773.                )))
  1774.         (while badies
  1775.           (dired-insert-subdir (car (car badies))
  1776.                        (cdr (car badies)) nil t)
  1777.           (setq badies (cdr badies))))
  1778.          ;; We can't use dired-save-excursion here, because we are
  1779.          ;; rewriting the entire listing, and not just changing a single
  1780.          ;; file line.
  1781.          (or (if ofile
  1782.              (dired-goto-file ofile)
  1783.            (if osub
  1784.                (dired-goto-subdir osub)))
  1785.          (progn
  1786.            (goto-char opoint)
  1787.            (beginning-of-line)
  1788.            (skip-chars-forward "^\n\r" (+ (point) ocol))))
  1789.          (dired-update-mode-line t)
  1790.          (dired-update-mode-line-modified t))))))
  1791.  
  1792. (defun dired-indent-listing (start end)
  1793.   ;; Indent a dired listing.
  1794.   (let (indent-tabs-mode)
  1795.     (indent-rigidly start end 2)
  1796.     ;; Quote any null lines that shouldn't be.
  1797.     (save-excursion
  1798.       (goto-char start)
  1799.       (while (search-forward "\n\n" end t)
  1800.     (forward-char -2)
  1801.     (if (looking-at dired-subdir-regexp)
  1802.         (goto-char (match-end 3))
  1803.       (progn
  1804.         (forward-char 1)
  1805.         (insert " ")))))))
  1806.  
  1807.  
  1808. ;;;; ------------------------------------------------------------
  1809. ;;;; Reverting a dired buffer, or specific file lines within it.
  1810. ;;;; ------------------------------------------------------------
  1811.  
  1812. (defun dired-revert (&optional arg noconfirm)
  1813.   ;; Reread the dired buffer.  Must also be called after
  1814.   ;; dired-internal-switches have changed.
  1815.   ;; Should not fail even on completely garbaged buffers.
  1816.   ;; Preserves old cursor, marks/flags, hidden-p.
  1817.   (widen)                ; just in case user narrowed
  1818.   (let ((opoint (point))
  1819.     (ofile (dired-get-filename nil t))
  1820.     (hidden-subdirs (dired-remember-hidden))
  1821.     ;; switches for top-level dir
  1822.     (oswitches (or (nth 3 (nth (1- (length dired-subdir-alist))
  1823.                    dired-subdir-alist))
  1824.                (delq ?R (copy-sequence dired-internal-switches))))
  1825.     ;; all other subdirs
  1826.     (old-subdir-alist (cdr (reverse dired-subdir-alist)))
  1827.     (omitted-subdirs (dired-remember-omitted))
  1828.     ;; do this after dired-remember-hidden, since this unhides
  1829.     (mark-alist (dired-remember-marks (point-min) (point-max)))
  1830.     (kill-files-p (save-excursion
  1831.             (goto-char (point))
  1832.             (search-forward
  1833.              (concat (char-to-string ?\r)
  1834.                  (regexp-quote
  1835.                   (char-to-string
  1836.                    dired-kill-marker-char)))
  1837.              nil t)))
  1838.     buffer-read-only)
  1839.     ;; This is bogus, as it will not handle all the ways that efs uses cache.
  1840.     ;; Better to just use the fact that revert-buffer-function is a
  1841.     ;; buffer-local variable, and reset it to something that knows about
  1842.     ;; cache.
  1843.     ;; (dired-uncache
  1844.     ;;   (if (consp dired-directory) (car dired-directory) dired-directory))
  1845.     ;; treat top level dir extra (it may contain wildcards)
  1846.     (let ((dired-after-readin-hook nil)
  1847.       ;; don't run that hook for each subdir...
  1848.       (dired-omit-files nil)
  1849.       (dired-internal-switches oswitches))
  1850.       (dired-readin dired-directory (current-buffer)
  1851.             ;; Don't test for wildcards by checking string=
  1852.             ;; default-directory and dired-directory
  1853.             ;; in case default-directory got munged.
  1854.             (or (consp dired-directory)
  1855.             (null (file-directory-p dired-directory))))
  1856.       ;; The R-switch will clobber sorting of subdirs.
  1857.       ;; What is the right thing to do here?
  1858.       (dired-insert-old-subdirs old-subdir-alist))
  1859.     (dired-mark-remembered mark-alist)    ; mark files that were marked
  1860.     (if kill-files-p (dired-do-hide dired-kill-marker-char))
  1861.     (run-hooks 'dired-after-readin-hook)    ; no need to narrow
  1862.     ;; omit-expunge after the readin hook
  1863.     (save-excursion
  1864.       (mapcar (function (lambda (dir)
  1865.               (if (dired-goto-subdir dir)
  1866.                   (dired-omit-expunge))))
  1867.           omitted-subdirs))
  1868.     ;; hide subdirs that were hidden
  1869.     (save-excursion
  1870.       (mapcar (function (lambda (dir)
  1871.               (if (dired-goto-subdir dir)
  1872.                   (dired-hide-subdir 1))))
  1873.           hidden-subdirs))
  1874.     ;; Try to get back to where we were
  1875.     (or (and ofile (dired-goto-file ofile))
  1876.     (goto-char opoint))
  1877.     (dired-move-to-filename)
  1878.     (dired-update-mode-line t)
  1879.     (dired-update-mode-line-modified t)))
  1880.  
  1881. (defun dired-do-redisplay (&optional arg)
  1882.   "Redisplay all marked (or next ARG) files."
  1883.   (interactive "P")
  1884.   ;; message instead of making dired-map-over-marks show-progress is
  1885.   ;; much faster
  1886.   (dired-map-over-marks (let ((fname (dired-get-filename)))
  1887.               (dired-uncache fname nil)
  1888.               (message "Redisplaying %s..." fname)
  1889.               (dired-update-file-line fname))
  1890.             arg)
  1891.   (dired-update-mode-line-modified t)
  1892.   (message "Redisplaying...done"))
  1893.  
  1894. (defun dired-redisplay-subdir (&optional arg)
  1895.   "Redisplay the current subdirectory.
  1896. With a prefix prompts for listing switches."
  1897.   (interactive "P")
  1898.   (let ((switches (and arg (dired-make-switches-list
  1899.                 (read-string "Switches for listing: "
  1900.                      (dired-make-switches-string
  1901.                       dired-internal-switches)))))
  1902.     (dir (dired-current-directory))
  1903.     (opoint (point))
  1904.     (ofile (dired-get-filename nil t)))
  1905.     (or switches
  1906.     (setq switches (nth 3 (assoc dir dired-subdir-alist))))
  1907.     (or switches
  1908.     (setq switches (delq ?R (copy-sequence dired-internal-switches))))
  1909.     (message "Redisplaying %s..." dir)
  1910.     (dired-uncache dir t)
  1911.     (dired-insert-subdir dir switches)
  1912.     (dired-update-mode-line-modified t)
  1913.     (or (and ofile (dired-goto-file ofile)) (goto-char opoint))
  1914.     (message "Redisplaying %s... done" dir)))
  1915.  
  1916. (defun dired-update-file-line (file)
  1917.   ;; Delete the current line, and insert an entry for FILE.
  1918.   ;; Does not update other dired buffers.  Use dired-relist-file for that.
  1919.   (let* ((start (save-excursion (skip-chars-backward "^\n\r") (point)))
  1920.      (char (char-after start)))
  1921.     (dired-save-excursion
  1922.      ;; don't remember omit marks
  1923.      (if (memq char (list ?\040 dired-omit-marker-char))
  1924.      (setq char nil))
  1925.      ;; Delete the current-line. Even though dired-add-entry will not
  1926.      ;; insert duplicates, the file for the current line may not be the same as
  1927.      ;; FILE. eg. dired-do-compress
  1928.      (delete-region (save-excursion (skip-chars-backward "^\n\r") (1- (point)))
  1929.             (progn (skip-chars-forward "^\n\r") (point)))
  1930.      ;; dired-add-entry inserts at the end of the previous line.
  1931.      (forward-char 1)
  1932.      (dired-add-entry file char t))))
  1933.  
  1934. ;;; Subroutines of dired-revert
  1935. ;;; Some of these are also used when inserting subdirs.
  1936.  
  1937. ;; Don't want to remember omit marks, in case omission regexps
  1938. ;; were changed, before the dired-revert. If we don't unhide
  1939. ;; omitted files, we won't see their marks. Therefore we use
  1940. ;; dired-omit-unhide-region.
  1941.  
  1942. (defun dired-remember-marks (beg end)
  1943.   ;; Return alist of files and their marks, from BEG to END.
  1944.   (if selective-display            ; must unhide to make this work.
  1945.       (let (buffer-read-only)
  1946.     (subst-char-in-region (point-min) (point-max) ?\r ?\n)
  1947.     (dired-do-hide dired-omit-marker-char)))
  1948.   (let (fil chr alist)
  1949.     (save-excursion
  1950.       (goto-char beg)
  1951.       (while (re-search-forward dired-re-mark end t)
  1952.     (if (setq fil (dired-get-filename nil t))
  1953.         (setq chr (preceding-char)
  1954.           alist (cons (cons fil chr) alist)))))
  1955.     alist))
  1956.  
  1957. (defun dired-mark-remembered (alist)
  1958.   ;; Mark all files remembered in ALIST.
  1959.   (let (elt fil chr)
  1960.     (while alist
  1961.       (setq elt (car alist)
  1962.         alist (cdr alist)
  1963.         fil (car elt)
  1964.         chr (cdr elt))
  1965.       (if (dired-goto-file fil)
  1966.       (save-excursion
  1967.         (beginning-of-line)
  1968.         (dired-substitute-marker (point) (following-char) chr))))))
  1969.  
  1970. (defun dired-remember-hidden ()
  1971.   ;; Return a list of all hidden subdirs.
  1972.   (let ((l dired-subdir-alist) dir result min)
  1973.     (while l
  1974.       (setq dir (car (car l))
  1975.         min (dired-get-subdir-min (car l))
  1976.         l (cdr l))
  1977.       (if (and (>= min (point-min)) (<= min (point-max))
  1978.            (dired-subdir-hidden-p dir))
  1979.       (setq result (cons dir result))))
  1980.     result))
  1981.  
  1982. (defun dired-insert-old-subdirs (old-subdir-alist)
  1983.   ;; Try to insert all subdirs that were displayed before
  1984.   (let (elt dir switches)
  1985.     (while old-subdir-alist
  1986.       (setq elt (car old-subdir-alist)
  1987.         old-subdir-alist (cdr old-subdir-alist)
  1988.         dir (car elt)
  1989.         switches (or (nth 3 elt) dired-internal-switches))
  1990.       (condition-case ()
  1991.       (dired-insert-subdir dir switches)
  1992.     (error nil)))))
  1993.  
  1994. (defun dired-uncache (file dir-p)
  1995.   ;; Remove directory DIR from any directory cache.
  1996.   ;; If DIR-P is non-nil, then FILE is a directory
  1997.   (let ((handler (find-file-name-handler file 'dired-uncache)))
  1998.     (if handler
  1999.     (funcall handler 'dired-uncache file dir-p))))
  2000.  
  2001.  
  2002. ;;;; -------------------------------------------------------------
  2003. ;;;; Inserting subdirectories
  2004. ;;;; -------------------------------------------------------------
  2005.  
  2006. (defun dired-maybe-insert-subdir (dirname &optional
  2007.                       switches no-error-if-not-dir-p)
  2008.   "Insert this subdirectory into the same dired buffer.
  2009. If it is already present, just move to it (type \\[dired-do-redisplay] to 
  2010.   refresh), else inserts it at its natural place (as ls -lR would have done).
  2011. With a prefix arg, you may edit the ls switches used for this listing.
  2012.   You can add `R' to the switches to expand the whole tree starting at
  2013.   this subdirectory.
  2014. This function takes some pains to conform to ls -lR output."
  2015.   (interactive
  2016.    (list (dired-get-filename)
  2017.      (if current-prefix-arg
  2018.          (dired-make-switches-list
  2019.           (read-string "Switches for listing: "
  2020.                (dired-make-switches-string
  2021.                 dired-internal-switches))))))
  2022.   (let ((opoint (point)))
  2023.     ;; We don't need a marker for opoint as the subdir is always
  2024.     ;; inserted *after* opoint.
  2025.     (setq dirname (file-name-as-directory dirname))
  2026.     (or (and (not switches)
  2027.          (dired-goto-subdir dirname))
  2028.     (dired-insert-subdir dirname switches no-error-if-not-dir-p))
  2029.     ;; Push mark so that it's easy to find back.  Do this after the
  2030.     ;; insert message so that the user sees the `Mark set' message.
  2031.     (push-mark opoint)))
  2032.  
  2033. (defun dired-insert-subdir (dir-or-list &optional
  2034.                     switches no-error-if-not-dir-p no-posn)
  2035.   "Insert this subdirectory into the same dired buffer.
  2036. If it is already present, overwrites previous entry,
  2037.   else inserts it at its natural place (as ls -lR would have done).
  2038. With a prefix arg, you may edit the ls switches used for this listing.
  2039.   You can add `R' to the switches to expand the whole tree starting at
  2040.   this subdirectory.
  2041. This function takes some pains to conform to ls -lR output."
  2042.   ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
  2043.   ;; Prospero where dired-ls does the right thing, but
  2044.   ;; file-directory-p has not been redefined.
  2045.   ;; SWITCHES should be a list.
  2046.   ;; If NO-POSN is non-nil, doesn't bother position the point at
  2047.   ;; the first nontrivial file line.  This can be used as an efficiency
  2048.   ;; hack when calling this from a program.
  2049.   (interactive
  2050.    (list (dired-get-filename)
  2051.      (if current-prefix-arg
  2052.          (dired-make-switches-list
  2053.           (read-string "Switches for listing: "
  2054.                (dired-make-switches-string
  2055.                 dired-internal-switches))))))
  2056.   (let ((dirname (if (consp dir-or-list) (car dir-or-list) dir-or-list)))
  2057.     (setq dirname (file-name-as-directory (expand-file-name dirname)))
  2058.     (or (dired-in-this-tree dirname (expand-file-name default-directory))
  2059.     (error  "%s: not in this directory tree" dirname))
  2060.     (or no-error-if-not-dir-p
  2061.     (file-directory-p dirname)
  2062.     (error  "Attempt to insert a non-directory: %s" dirname))
  2063.     (if switches
  2064.     (or (dired-compatible-switches-p dired-internal-switches switches)
  2065.         (error "Cannot have subdirs with %s and %s switches together."
  2066.            (dired-make-switches-string dired-internal-switches)
  2067.            (dired-make-switches-string switches)))
  2068.       (setq switches dired-internal-switches))
  2069.     (let ((elt (assoc dirname dired-subdir-alist))
  2070.       mark-alist opoint-max buffer-read-only)
  2071.       (if (memq ?R switches)
  2072.       ;; avoid duplicated subdirs
  2073.       (progn
  2074.         (setq mark-alist (dired-kill-tree dirname t))
  2075.         (dired-insert-subdir-newpos dirname))
  2076.     (if elt
  2077.         ;; If subdir is already present, remove it and remember its marks
  2078.         (setq mark-alist (dired-insert-subdir-del elt))
  2079.       ;; else move to new position
  2080.       (dired-insert-subdir-newpos dirname)))
  2081.       (setq opoint-max (point-max))
  2082.       (condition-case nil
  2083.       (dired-insert-subdir-doupdate
  2084.        dirname (dired-insert-subdir-doinsert dir-or-list switches)
  2085.        switches elt mark-alist)
  2086.     (quit ; watch out for aborted inserts
  2087.      (and (= opoint-max (point-max))
  2088.           (null elt)
  2089.           (= (preceding-char) ?\n)
  2090.           (delete-char -1))
  2091.      (signal 'quit nil))))
  2092.     (or no-posn (dired-initial-position dirname))))
  2093.  
  2094. (defun dired-do-insert-subdir ()
  2095.   "Insert all marked subdirectories in situ that are not yet inserted.
  2096. Non-directories are silently ignored."
  2097.   (interactive)
  2098.   (let ((files (or (dired-get-marked-files)
  2099.            (error "No files marked."))))
  2100.     (while files
  2101.       (if (file-directory-p (car files))
  2102.       (save-excursion (dired-maybe-insert-subdir (car files))))
  2103.       (setq files (cdr files)))))
  2104.  
  2105. ;;; Utilities for inserting subdirectories
  2106.  
  2107. (defun dired-insert-subdir-newpos (new-dir)
  2108.   ;; Find pos for new subdir, according to tree order.
  2109.   (let ((alist dired-subdir-alist) elt dir new-pos)
  2110.     (while alist
  2111.       (setq elt (car alist)
  2112.         alist (cdr alist)
  2113.         dir (car elt))
  2114.       (if (dired-tree-lessp dir new-dir)
  2115.       ;; Insert NEW-DIR after DIR
  2116.       (setq new-pos (dired-get-subdir-max elt)
  2117.         alist nil)))
  2118.     (goto-char new-pos))
  2119.   (insert "\n")
  2120.   (point))
  2121.  
  2122. (defun dired-insert-subdir-del (element)
  2123.   ;; Erase an already present subdir (given by ELEMENT) from buffer.
  2124.   ;; Move to that buffer position.  Return a mark-alist.
  2125.   (let ((begin-marker (dired-get-subdir-min element)))
  2126.     (goto-char begin-marker)
  2127.     ;; Are at beginning of subdir (and inside it!).  Now determine its end:
  2128.     (goto-char (dired-subdir-max))
  2129.     (prog1
  2130.     (dired-remember-marks begin-marker (point))
  2131.       (delete-region begin-marker (point)))))
  2132.  
  2133. (defun dired-insert-subdir-doinsert (dir-or-list switches)
  2134.   ;; Insert ls output after point and put point on the correct
  2135.   ;; position for the subdir alist.
  2136.   ;; Return the boundary of the inserted text (as list of BEG and END).
  2137.   ;; SWITCHES should be a non-nil list.
  2138.   (let ((begin (point))
  2139.     (dirname (if (consp dir-or-list) (car dir-or-list) dir-or-list))
  2140.     end)
  2141.     (message "Reading directory %s..." dirname)
  2142.     (if (string-equal dirname (car (car (reverse dired-subdir-alist))))
  2143.     ;; top level directory may contain wildcards:
  2144.     (let ((dired-internal-switches switches))
  2145.       (dired-readin-insert dired-directory
  2146.                    (null (file-directory-p dired-directory))))
  2147.       (let ((switches (dired-make-switches-string switches))
  2148.         (insert-directory-program dired-ls-program))
  2149.     (if (consp dir-or-list)
  2150.         (progn
  2151.           (insert "list wildcard\n")
  2152.           (mapcar
  2153.            (function
  2154.         (lambda (x)
  2155.           (insert-directory x switches t)))
  2156.            (cdr dir-or-list)))
  2157.       (insert-directory dirname switches nil t))))
  2158.     (message "Reading directory %s...done" dirname)
  2159.     (setq end (point-marker))
  2160.     (dired-indent-listing begin end)
  2161.     (dired-insert-set-properties begin end)
  2162.     ;;  call dired-insert-headerline afterwards, as under VMS dired-ls
  2163.     ;;  does insert the headerline itself and the insert function just
  2164.     ;;  moves point.
  2165.     ;;  Need a marker for END as this inserts text.
  2166.     (goto-char begin)
  2167.     (dired-insert-headerline dirname)
  2168.     ;; point is now like in dired-build-subdir-alist
  2169.     (prog1
  2170.     (list begin (marker-position end))
  2171.       (set-marker end nil))))
  2172.  
  2173. (defun dired-insert-subdir-doupdate (dirname beg-end switches elt mark-alist)
  2174.   ;; Point is at the correct subdir alist position for ELT,
  2175.   ;; BEG-END is the subdir-region (as list of begin and end).
  2176.   ;; SWITCHES must be a non-nil list.
  2177.   (if (memq ?R switches)
  2178.       ;; This will remove ?R from switches on purpose.
  2179.       (let ((dired-internal-switches (delq ?R switches)))
  2180.     (dired-build-subdir-alist))
  2181.     (if elt
  2182.     (progn
  2183.       (set-marker (dired-get-subdir-min elt) (point-marker))
  2184.       (setcar (nthcdr 3 elt) switches)
  2185.       (if dired-verify-modtimes
  2186.           (dired-set-file-modtime dirname dired-subdir-alist)))
  2187.       (dired-alist-add dirname (point-marker) dired-omit-files switches)))
  2188.   (save-excursion
  2189.     (let ((begin (nth 0 beg-end))
  2190.       (end (nth 1 beg-end)))
  2191.       (goto-char begin)
  2192.       (save-restriction
  2193.     (narrow-to-region begin end)
  2194.     ;; hook may add or delete lines, but the subdir boundary
  2195.     ;; marker floats
  2196.     (run-hooks 'dired-after-readin-hook)
  2197.     (if mark-alist (dired-mark-remembered mark-alist))
  2198.     (dired-do-hide dired-kill-marker-char)
  2199.     (if (if elt (nth 2 elt) dired-omit-files)
  2200.         (dired-omit-expunge nil t))))))
  2201.  
  2202.  
  2203. ;;;; --------------------------------------------------------------
  2204. ;;;; Dired motion commands -- moving around in the dired buffer.
  2205. ;;;; --------------------------------------------------------------
  2206.     
  2207. (defun dired-next-line (arg)
  2208.   "Move down lines then position at filename.
  2209. Optional prefix ARG says how many lines to move; default is one line."
  2210.   (interactive "_p")
  2211.   (condition-case err
  2212.       (next-line arg)
  2213.     (error
  2214.      (if (eobp)
  2215.      (error "End of buffer")
  2216.        (error "%s" err))))
  2217.   (dired-move-to-filename)
  2218.   (dired-update-mode-line))
  2219.  
  2220. (defun dired-previous-line (arg)
  2221.   "Move up lines then position at filename.
  2222. Optional prefix ARG says how many lines to move; default is one line."
  2223.   (interactive "_p")
  2224.   (previous-line arg)
  2225.   (dired-move-to-filename)
  2226.   (dired-update-mode-line))
  2227.  
  2228. (defun dired-scroll-up (arg)
  2229.   "Dired version of scroll up.
  2230. Scroll text of current window upward ARG lines; or near full screen if no ARG.
  2231. When calling from a program, supply a number as argument or nil."
  2232.   (interactive "_P")
  2233.   (scroll-up arg)
  2234.   (dired-move-to-filename)
  2235.   (dired-update-mode-line))
  2236.  
  2237. (defun dired-scroll-down (arg)
  2238.   "Dired version of scroll-down.
  2239. Scroll text of current window down ARG lines; or near full screen if no ARG.
  2240. When calling from a program, supply a number as argument or nil."
  2241.   (interactive "_P")
  2242.   (scroll-down arg)
  2243.   (dired-move-to-filename)
  2244.   (dired-update-mode-line))
  2245.  
  2246. (defun dired-beginning-of-buffer (arg)
  2247.   "Dired version of `beginning of buffer'."
  2248.   (interactive "_P")
  2249.   (beginning-of-buffer arg)
  2250.   (dired-update-mode-line))
  2251.  
  2252. (defun dired-end-of-buffer (arg)
  2253.   "Dired version of `end-of-buffer'."
  2254.   (interactive "_P")
  2255.   (end-of-buffer arg)
  2256.   (while (not (or (dired-move-to-filename) (dired-get-subdir) (bobp)))
  2257.     (forward-line -1))
  2258.   (dired-update-mode-line t))
  2259.  
  2260. (defun dired-next-dirline (arg &optional opoint)
  2261.   "Goto ARG'th next directory file line."
  2262.   (interactive "_p")
  2263.   (if dired-re-dir
  2264.       (progn
  2265.     (dired-check-ls-l)
  2266.     (or opoint (setq opoint (point)))
  2267.     (if (if (> arg 0)
  2268.         (re-search-forward dired-re-dir nil t arg)
  2269.           (beginning-of-line)
  2270.           (re-search-backward dired-re-dir nil t (- arg)))
  2271.         (progn
  2272.           (dired-move-to-filename)        ; user may type `i' or `f'
  2273.           (dired-update-mode-line))
  2274.       (goto-char opoint)
  2275.       (error "No more subdirectories")))))
  2276.  
  2277. (defun dired-prev-dirline (arg)
  2278.   "Goto ARG'th previous directory file line."
  2279.   (interactive "_p")
  2280.   (dired-next-dirline (- arg)))
  2281.  
  2282. (defun dired-next-marked-file (arg &optional wrap opoint)
  2283.   "Move to the next marked file, wrapping around the end of the buffer."
  2284.   (interactive "_p\np")
  2285.   (or opoint (setq opoint (point))) ; return to where interactively started
  2286.   (if (if (> arg 0)
  2287.       (re-search-forward dired-re-mark nil t arg)
  2288.     (beginning-of-line)
  2289.     (re-search-backward dired-re-mark nil t (- arg)))
  2290.       (dired-move-to-filename)
  2291.     (if (null wrap)
  2292.     (progn
  2293.       (goto-char opoint)
  2294.       (error "No next marked file"))
  2295.       (message "(Wraparound for next marked file)")
  2296.       (goto-char (if (> arg 0) (point-min) (point-max)))
  2297.       (dired-next-marked-file arg nil opoint)))
  2298.   (dired-update-mode-line))
  2299.  
  2300. (defun dired-prev-marked-file (arg &optional wrap)
  2301.   "Move to the previous marked file, wrapping around the end of the buffer."
  2302.   (interactive "_p\np")
  2303.   (dired-next-marked-file (- arg) wrap)
  2304.   (dired-update-mode-line))
  2305.  
  2306. (defun dired-goto-file (file)
  2307.   "Goto file line of FILE in this dired buffer."
  2308.   ;; Return value of point on success, else nil.
  2309.   ;; FILE must be an absolute pathname.
  2310.   ;; Loses if FILE contains control chars like "\007" for which ls
  2311.   ;; either inserts "?" or "\\007" into the buffer, so we won't find
  2312.   ;; it in the buffer.
  2313.   (interactive
  2314.    (prog1                ; let push-mark display its message
  2315.        (list
  2316.     (let* ((dired-completer-buffer (current-buffer))
  2317.            (dired-completer-switches dired-internal-switches)
  2318.            (stack (reverse
  2319.                (mapcar (function
  2320.                 (lambda (x)
  2321.                   (dired-abbreviate-file-name (car x))))
  2322.                    dired-subdir-alist)))
  2323.            (initial (car stack))
  2324.            (dired-goto-file-history (cdr stack))
  2325.            dired-completer-cache)
  2326.       (expand-file-name
  2327.        (dired-completing-read "Goto file: "
  2328.                   'dired-goto-file-completer
  2329.                   nil t initial 'dired-goto-file-history))))
  2330.      (push-mark)))
  2331.   (setq file (directory-file-name file)) ; does no harm if no directory
  2332.   (let (found case-fold-search)
  2333.     (save-excursion
  2334.       (if (dired-goto-subdir (or (file-name-directory file)
  2335.                  (error "Need absolute pathname for %s"
  2336.                     file)))
  2337.       (let* ((base (file-name-nondirectory file))
  2338.          ;; filenames are preceded by SPC, this makes
  2339.          ;; the search faster (e.g. for the filename "-"!).
  2340.          (search (concat " " (dired-make-filename-string base t)))
  2341.          (boundary (dired-subdir-max))
  2342.          fn)
  2343.         (while (and (not found) (search-forward search boundary 'move))
  2344.           ;; Match could have BASE just as initial substring or
  2345.           ;; or in permission bits or date or
  2346.           ;; not be a proper filename at all:
  2347.           (if (and (setq fn (dired-get-filename 'no-dir t))
  2348.                (string-equal fn base))
  2349.           ;; Must move to filename since an (actually
  2350.           ;; correct) match could have been elsewhere on the
  2351.           ;; line (e.g. "-" would match somewhere in the
  2352.           ;; permission bits).
  2353.           (setq found (dired-move-to-filename)))))))
  2354.     (and found
  2355.      ;; return value of point (i.e., FOUND):
  2356.      (prog1
  2357.          (goto-char found)
  2358.        (dired-update-mode-line)))))
  2359.  
  2360. ;;; Moving by subdirectories
  2361.  
  2362. (defun dired-up-directory (arg)
  2363.   "Move to the ARG'th (prefix arg) parent directory of current directory.
  2364. Always stays within the current tree dired buffer.  Will insert new
  2365. subdirectories if necessary."
  2366.   (interactive "p")
  2367.   (if (< arg 0) (error "Can't go up a negative number of directories!"))
  2368.   (or (zerop arg)
  2369.       (let* ((dir (dired-current-directory))
  2370.          (n arg)
  2371.          (up dir))
  2372.     (while (> n 0)
  2373.       (setq up (file-name-directory (directory-file-name up))
  2374.         n (1- n)))
  2375.     (if (and (< (length up) (length dired-directory))
  2376.          (dired-in-this-tree dired-directory up))
  2377.         (if (or (memq 'create-top-dir dired-no-confirm)
  2378.             (y-or-n-p
  2379.              (format "Insert new top dir %s and rename buffer? "
  2380.                  (dired-abbreviate-file-name up))))
  2381.         (let ((newname (let (buff)
  2382.                   (unwind-protect
  2383.                       (buffer-name
  2384.                        (setq buff
  2385.                          (create-file-buffer
  2386.                           (directory-file-name up))))
  2387.                     (kill-buffer buff))))
  2388.               (buffer-read-only nil))
  2389.           (push-mark)
  2390.           (widen)
  2391.           (goto-char (point-min))
  2392.           (insert-before-markers "\n")
  2393.           (forward-char -1)
  2394.           (dired-insert-subdir-doupdate
  2395.            up (dired-insert-subdir-doinsert up dired-internal-switches)
  2396.            dired-internal-switches nil nil)
  2397.           (dired-initial-position up)
  2398.           (rename-buffer newname)
  2399.           (dired-unadvertise default-directory)
  2400.           (setq default-directory up
  2401.             dired-directory up)
  2402.           (dired-advertise)))
  2403.       (dired-maybe-insert-subdir up)))))
  2404.  
  2405. (defun dired-down-directory ()
  2406.   "Go down in the dired tree.
  2407. Moves to the first subdirectory of the current directory, which exists in
  2408. the dired buffer.  Does not take a prefix argument."
  2409.   ;; What would a prefix mean here?
  2410.   (interactive)
  2411.   (let ((dir (dired-current-directory)) ; has slash
  2412.     (rest (reverse dired-subdir-alist))
  2413.     pos elt)
  2414.     (while rest
  2415.       (setq elt (car rest))
  2416.       (if (dired-in-this-tree (directory-file-name (car elt)) dir)
  2417.       (setq rest nil
  2418.         pos (dired-goto-subdir (car elt)))
  2419.     (setq rest (cdr rest))))
  2420.     (prog1
  2421.     (if pos
  2422.         (progn
  2423.           (push-mark)
  2424.           (goto-char pos))
  2425.       (error "At the bottom"))
  2426.       (dired-update-mode-line t))))
  2427.  
  2428. (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
  2429.   "Go to next subdirectory, regardless of level."
  2430.   ;; Use 0 arg to go to this directory's header line.
  2431.   ;; NO-SKIP prevents moving to end of header line, returning whatever
  2432.   ;; position was found in dired-subdir-alist.
  2433.   (interactive "p")
  2434.   (let ((this-dir (dired-current-directory))
  2435.     pos index)
  2436.     ;; nth with negative arg does not return nil but the first element
  2437.     (setq index (- (length dired-subdir-alist)
  2438.            (length (memq (assoc this-dir dired-subdir-alist)
  2439.                  dired-subdir-alist))
  2440.            arg))
  2441.     (setq pos (if (>= index 0)
  2442.           (dired-get-subdir-min (nth index dired-subdir-alist))))
  2443.     (if pos
  2444.     (if no-skip
  2445.         (goto-char pos)
  2446.       (goto-char pos)
  2447.       (skip-chars-forward "^\r\n")
  2448.       (if (= (following-char) ?\r)
  2449.           (skip-chars-backward "." (- (point) 3)))
  2450.       (dired-update-mode-line t)
  2451.       (point))
  2452.       (if no-error-if-not-found
  2453.       nil                ; return nil if not found
  2454.     (error "%s directory" (if (> arg 0) "Last" "First"))))))
  2455.  
  2456. (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
  2457.   "Go to previous subdirectory, regardless of level.
  2458. When called interactively and not on a subdir line, go to this subdir's line."
  2459.   (interactive
  2460.    (list (if current-prefix-arg
  2461.          (prefix-numeric-value current-prefix-arg)
  2462.        ;; if on subdir start already, don't stay there!
  2463.        (if (dired-get-subdir) 1 0))))
  2464.   (dired-next-subdir (- arg) no-error-if-not-found no-skip))
  2465.  
  2466. (defun dired-goto-subdir (dir)
  2467.   "Goto end of header line of DIR in this dired buffer.
  2468. Return value of point on success, otherwise return nil.
  2469. The next char is either \\n, or \\r if DIR is hidden."
  2470.   (interactive
  2471.    (prog1                ; let push-mark display its message
  2472.        (list
  2473.     (let* ((table (mapcar
  2474.                (function
  2475.             (lambda (x)
  2476.               (list (dired-abbreviate-file-name
  2477.                  (car x)))))
  2478.                dired-subdir-alist))
  2479.            (stack (reverse (mapcar 'car table)))
  2480.            (initial (car stack))
  2481.            (dired-goto-file-history (cdr stack)))
  2482.       (expand-file-name
  2483.        (dired-completing-read "Goto subdirectory " table nil t
  2484.                   initial 'dired-goto-file-history))))
  2485.      (push-mark)))
  2486.   (setq dir (file-name-as-directory dir))
  2487.   (let ((elt (assoc dir dired-subdir-alist)))
  2488.     (and elt
  2489.      ;; need to make sure that we get where we're going.
  2490.      ;; beware: narrowing might be in effect
  2491.      (eq (goto-char (dired-get-subdir-min elt)) (point))
  2492.      (progn
  2493.        ;; dired-subdir-hidden-p and dired-add-entry depend on point being
  2494.        ;; at either \n or looking-at ...\r after this function succeeds.
  2495.        (skip-chars-forward "^\r\n")
  2496.        (if (= (preceding-char) ?.)
  2497.            (skip-chars-backward "." (- (point) 3)))
  2498.        (if (interactive-p) (dired-update-mode-line))
  2499.        (point)))))
  2500.  
  2501. ;;; Internals for motion commands
  2502.  
  2503. (defun dired-update-mode-line (&optional force)
  2504.   "Updates the mode line in dired according to the position of the point.
  2505. Normally this uses a cache of the boundaries of the current subdirectory,
  2506. but if the optional argument FORCE is non-nil, then modeline is always
  2507. updated and the cache is recomputed."
  2508.   (if (or force
  2509.       (>= (point) dired-curr-subdir-max)
  2510.       (< (point) dired-curr-subdir-min))
  2511.       (let ((alist dired-subdir-alist)
  2512.         min max)
  2513.     (while (and alist (< (point)
  2514.                  (setq min (dired-get-subdir-min (car alist)))))
  2515.       (setq alist (cdr alist)
  2516.         max min))
  2517.     (setq dired-curr-subdir-max (or max (point-max-marker))
  2518.           dired-curr-subdir-min (or min (point-min-marker))
  2519.           dired-subdir-omit (nth 2 (car alist)))
  2520.     (dired-sort-set-modeline (nth 3 (car alist))))))
  2521.  
  2522. (defun dired-manual-move-to-filename (&optional raise-error bol eol)
  2523.   "In dired, move to first char of filename on this line.
  2524. Returns position (point) or nil if no filename on this line."
  2525.   ;; This is the UNIX version.
  2526.   ;; have to be careful that we don't move to omitted files
  2527.   (let (case-fold-search)
  2528.     
  2529.     (or eol (setq eol (save-excursion (skip-chars-forward "^\r\n") (point))))
  2530.     (or bol (setq bol (progn (skip-chars-backward "^\r\n") (point))))
  2531.     
  2532.     (if (or (memq ?l dired-internal-switches)
  2533.         (memq ?g dired-internal-switches))
  2534.     (if (and
  2535.          (> (- eol bol) 17)         ; a valid file line must have at least
  2536.                     ; 17 chars. 2 leading, 10 perms,
  2537.                     ; separator, node #, separator, owner,
  2538.                     ; separator
  2539.          (goto-char (+ bol 17))
  2540.          (re-search-forward dired-re-month-and-time eol t))
  2541.         (point)
  2542.       (goto-char bol)
  2543.       (if raise-error
  2544.           (error "No file on this line")
  2545.         nil))
  2546.       ;; else ls switches don't contain -l.
  2547.       ;; Note that even if we make dired-move-to-filename and
  2548.       ;; dired-move-to-end-of-filename (and thus dired-get-filename)
  2549.       ;; work, all commands that gleaned information from the permission
  2550.       ;; bits (like dired-mark-directories) will cease to work properly.
  2551.       (if (= bol eol)
  2552.       (if raise-error
  2553.           (error "No file on this line")
  2554.         nil)
  2555.     ;; skip marker, if any
  2556.     (goto-char bol)
  2557.     (forward-char))
  2558.       ;; If we not going to use the l switch, and use nstd listings,
  2559.       ;; then we must bomb on files starting with spaces.
  2560.       (skip-chars-forward " \t")
  2561.       (point))))
  2562.  
  2563. (defun dired-manual-move-to-end-of-filename (&optional no-error bol eol)
  2564.   ;; Assumes point is at beginning of filename,
  2565.   ;; thus the rwx bit re-search-backward below will succeed in *this*
  2566.   ;; line if at all.  So, it should be called only after
  2567.   ;; (dired-move-to-filename t).
  2568.   ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
  2569.   ;; This is the UNIX version.
  2570.   (let ((bof (point))
  2571.     file-type modes-start case-fold-search)
  2572.     (or eol (setq eol (save-excursion (skip-chars-forward "^\r\n") (point))))
  2573.     (or bol (setq bol (save-excursion (skip-chars-backward "^\r\n") (point))))
  2574.     (and
  2575.      (null no-error)
  2576.      selective-display
  2577.      (eq (char-after (1- bol)) ?\r)
  2578.      (cond
  2579.       ((dired-subdir-hidden-p (dired-current-directory))
  2580.        (error
  2581.     (substitute-command-keys
  2582.      "File line is hidden. Type \\[dired-hide-subdir] to unhide.")))
  2583.       ((error
  2584.     (substitute-command-keys
  2585.      "File line is omitted. Type \\[dired-omit-toggle] to un-omit.")))))
  2586.     (if (or (memq ?l dired-internal-switches)
  2587.         (memq ?g dired-internal-switches))
  2588.     (if (save-excursion
  2589.           (goto-char bol)
  2590.           (re-search-forward
  2591.            "[^ ][-r][-w][^ ][-r][-w][^ ][-r][-w][^ ][-+ 0-9+]"
  2592.            bof t))
  2593.         (progn
  2594.           (setq modes-start (match-beginning 0)
  2595.             file-type (char-after modes-start))
  2596.           ;; Move point to end of name:
  2597.           (if (eq file-type ?l) ; symlink
  2598.           (progn
  2599.             (if (search-forward " -> " eol t)
  2600.             (goto-char (match-beginning 0))
  2601.               (goto-char eol))
  2602.             (and dired-ls-F-marks-symlinks
  2603.              (eq (preceding-char) ?@) ; link really marked?
  2604.              (memq ?F dired-internal-switches)
  2605.              (forward-char -1))
  2606.             (point))
  2607.         ;; else not a symbolic link
  2608.         (goto-char eol)
  2609.         ;; ls -lF marks dirs, sockets and executables with exactly
  2610.         ;; one trailing character. -F may not actually be honored, 
  2611.         ;; e.g. by an FTP ls in efs
  2612.         (and
  2613.          (memq ?F dired-internal-switches)
  2614.          (let ((char (preceding-char)))
  2615.            (or (and (eq char ?*) (or
  2616.                       (memq
  2617.                        (char-after (+ modes-start 3))
  2618.                        '(?x ?s ?t))
  2619.                       (memq
  2620.                        (char-after (+ modes-start 6))
  2621.                        '(?x ?s ?t))
  2622.                       (memq
  2623.                        (char-after (+ modes-start 9))
  2624.                        '(?x ?s ?t))))
  2625.                (and (eq char ?=) (eq file-type ?s))))
  2626.          (forward-char -1))
  2627.         ;; Skip back over /'s unconditionally.  It's not a valid
  2628.         ;; file name character.
  2629.         (skip-chars-backward "/")
  2630.         (point)))
  2631.       (and (null no-error)
  2632.            (error "No file on this line")))
  2633.       
  2634.       ;; A brief listing
  2635.       (if (eq (point) eol)
  2636.       (and (null no-error)
  2637.            (error "No file on this line"))
  2638.     (goto-char eol)
  2639.     (if (and (memq (preceding-char) '(?@ ?* ?=))
  2640.          (memq ?F dired-internal-switches))
  2641.         ;; A guess, since without a long listing, we can't be sure.
  2642.         (forward-char -1))
  2643.     (skip-chars-backward "/")
  2644.     (point)))))
  2645.  
  2646. (defun dired-goto-next-nontrivial-file ()
  2647.   ;; Position point on first nontrivial file after point.
  2648.   ;; Does not move into the next sudir.
  2649.   ;; If point is on a file line, moves to that file.
  2650.   ;; This does not move to omitted files.
  2651.   (skip-chars-backward "^\n\r")
  2652.   (if (= (preceding-char) ?\r)
  2653.       (forward-line 1))
  2654.   (let ((max (dired-subdir-max))
  2655.     file)
  2656.     (while (and (or (not (setq file (dired-get-filename 'no-dir t)))
  2657.             (string-match dired-trivial-filenames file))
  2658.         (< (point) max))
  2659.       (forward-line 1)))
  2660.   (dired-move-to-filename))
  2661.  
  2662. (defun dired-goto-next-file ()
  2663.   ;; Doesn't move out of current subdir. Does go to omitted files.
  2664.   ;; Returns the starting position of the file, or nil if none found.
  2665.   (let ((max (dired-subdir-max))
  2666.     found)
  2667.     (while (and (null (setq found (dired-move-to-filename))) (< (point) max))
  2668.       (skip-chars-forward "^\n\r")
  2669.       (forward-char 1))
  2670.     found))
  2671.  
  2672. ;; fluid vars used by dired-goto-file-completer
  2673. (defvar dired-completer-buffer nil)
  2674. (defvar dired-completer-switches nil)
  2675. (defvar dired-completer-cache nil)
  2676.  
  2677. (defun dired-goto-file-completer (string pred action)
  2678.   (save-excursion
  2679.     (set-buffer dired-completer-buffer)
  2680.     (let* ((saved-md (match-data))
  2681.        (file (file-name-nondirectory string))
  2682.        (dir (file-name-directory string))
  2683.        (xstring (expand-file-name string))
  2684.        (xdir (file-name-directory xstring))
  2685.        (exact (dired-goto-file xstring)))
  2686.       (unwind-protect
  2687.       (if (dired-goto-subdir xdir)
  2688.           (let ((table (cdr (assoc xdir dired-completer-cache)))
  2689.             fn result max)
  2690.         (or table
  2691.             (progn
  2692.               (setq table (make-vector 37 0))
  2693.               (mapcar (function
  2694.                    (lambda (ent)
  2695.                  (setq ent (directory-file-name
  2696.                         (car ent)))
  2697.                  (if (string-equal
  2698.                       (file-name-directory ent) xdir)
  2699.                      (intern
  2700.                       (concat
  2701.                        (file-name-nondirectory ent) "/")
  2702.                       table))))
  2703.                   dired-subdir-alist)
  2704.               (or (looking-at "\\.\\.\\.\n\r")
  2705.               (progn
  2706.                 (setq max (dired-subdir-max))
  2707.                 (while (and
  2708.                     (< (point) max)
  2709.                     (not
  2710.                      (setq fn
  2711.                        (dired-get-filename 'no-dir t))))
  2712.                   (forward-line 1))
  2713.                 (if fn
  2714.                 (progn
  2715.                   (or (intern-soft (concat fn "/") table)
  2716.                       (intern fn table))
  2717.                   (forward-line 1)
  2718.                   (while (setq fn
  2719.                            (dired-get-filename 'no-dir t))
  2720.                     (or (intern-soft (concat fn "/") table)
  2721.                     (intern fn table))
  2722.                     (forward-line 1))))))
  2723.               (setq dired-completer-cache (cons
  2724.                            (cons xdir table)
  2725.                            dired-completer-cache))))
  2726.         (cond
  2727.          ((null action)
  2728.           (setq result (try-completion file table))
  2729.           (if exact
  2730.               (if (stringp result)
  2731.               string
  2732.             t)
  2733.             (if (stringp result)
  2734.             (concat dir result)
  2735.               result)))
  2736.          ((eq action t)
  2737.           (setq result (all-completions file table))
  2738.           (if exact (cons "." result) result))
  2739.          ((eq 'lambda action)
  2740.           (and (or exact (intern-soft file table)))))))
  2741.     (store-match-data saved-md)))))
  2742.  
  2743. (defun dired-really-goto-file (file)
  2744.   ;; Goes to a file, even if it needs to insert it parent directory.
  2745.   (or (dired-goto-file file)
  2746.       (progn                ; refresh and try again
  2747.     (dired-insert-subdir (file-name-directory file))
  2748.     (dired-goto-file file))))
  2749.  
  2750. (defun dired-between-files ()
  2751.   ;; Point must be at beginning of line
  2752.   (save-excursion (not (dired-move-to-filename nil (point)))))
  2753.  
  2754. (defun dired-repeat-over-lines (arg function)
  2755.   ;; This version skips non-file lines.
  2756.   ;; Skips file lines hidden with selective display.
  2757.   ;; BACKWARDS means move backwards after each action.  This is not the same
  2758.   ;; as a negative arg, as that skips the current line.
  2759.   (beginning-of-line)
  2760.   (let* ((advance (cond ((> arg 0) 1) ((< arg 0) -1) (t nil)))
  2761.      (check-fun (if (eq advance 1) 'eobp 'bobp))
  2762.      (n (if (< arg 0) (- arg) arg))
  2763.      (wall (funcall check-fun))
  2764.      (done wall))
  2765.     (while (not done)
  2766.       (if advance
  2767.       (progn
  2768.         (while  (not (or (save-excursion (dired-move-to-filename))
  2769.                  (setq wall (funcall check-fun))))
  2770.           (forward-line advance))
  2771.         (or wall
  2772.         (progn
  2773.           (save-excursion (funcall function))
  2774.           (forward-line advance)
  2775.           (while (not (or (save-excursion (dired-move-to-filename))
  2776.                   (setq wall (funcall check-fun))))
  2777.             (forward-line advance))
  2778.           (setq done (or (zerop (setq n (1- n))) wall)))))
  2779.     (if (save-excursion (dired-move-to-filename))
  2780.         (save-excursion (funcall function)))
  2781.     (setq done t))))
  2782.   (dired-move-to-filename)
  2783.   ;; Note that if possible the point has now been moved to the beginning of
  2784.   ;; the file name.
  2785.   (dired-update-mode-line))
  2786.  
  2787.  
  2788. ;;;; ----------------------------------------------------------------
  2789. ;;;; Miscellaneous dired commands
  2790. ;;;; ----------------------------------------------------------------
  2791.  
  2792. (defun dired-quit ()
  2793.   "Bury the current dired buffer."
  2794.   (interactive)
  2795.   (bury-buffer))
  2796.  
  2797. (defun dired-undo ()
  2798.   "Undo in a dired buffer.
  2799. This doesn't recover lost files, it is just normal undo with temporarily
  2800. writeable buffer.  You can use it to recover marks, killed lines or subdirs."
  2801.   (interactive)
  2802.   (let ((lines (count-lines (point-min) (point-max)))
  2803.     buffer-read-only)
  2804.     (undo)
  2805.     ;; reset dired-subdir-alist, if a dir may have been affected
  2806.     ;; Is there a better way to guess this?
  2807.     (setq lines (- (count-lines (point-min) (point-max)) lines))
  2808.     (if (or (>= lines 2) (<= lines -2))
  2809.     (dired-build-subdir-alist)))
  2810.   (dired-update-mode-line-modified t)
  2811.   (dired-update-mode-line t))
  2812.  
  2813.  
  2814. ;;;; --------------------------------------------------------
  2815. ;;;; Immediate actions on files: visiting, viewing, etc.
  2816. ;;;; --------------------------------------------------------
  2817.  
  2818. (defun dired-find-file ()
  2819.   "In dired, visit the file or directory named on this line."
  2820.   (interactive)
  2821.   (let ((find-file-run-dired t))
  2822.     (find-file (dired-get-filename))))
  2823.  
  2824. (defun dired-view-file ()
  2825.   "In dired, examine a file in view mode, returning to dired when done.
  2826. When file is a directory, show it in this buffer if it is inserted;
  2827. otherwise, display it in another buffer."
  2828.   (interactive)
  2829.   (let ((file (dired-get-filename)))
  2830.     (if (file-directory-p file)
  2831.     (or (dired-goto-subdir file)
  2832.         (dired file))
  2833.       (view-file file))))
  2834.  
  2835. (defun dired-find-file-other-window (&optional displayp)
  2836.   "In dired, visit this file or directory in another window.
  2837. With a prefix, the file is displayed, but the window is not selected."
  2838.   (interactive "P")
  2839.   (if displayp
  2840.       (dired-display-file)
  2841.       (let ((find-file-run-dired t))
  2842.         (find-file-other-window (dired-get-filename)))))
  2843.  
  2844. ;; Only for Emacs 19
  2845. (defun dired-find-file-other-frame ()
  2846.   "In dired, visit this file or directory in another frame."
  2847.   (interactive)
  2848.   (let ((find-file-run-dired t))
  2849.     (find-file-other-frame (dired-get-filename))))
  2850.  
  2851. (defun dired-display-file ()
  2852.   "In dired, displays this file or directory in the other window."
  2853.   (interactive)
  2854.   (let ((find-file-run-dired t))
  2855.     (display-buffer (find-file-noselect (dired-get-filename)))))
  2856.  
  2857. ;; After an idea by wurgler@zippysun.math.uakron.edu (Tom Wurgler).
  2858. (defun dired-do-find-file (&optional arg)
  2859.   "Visit all marked files at once, and display them simultaneously.
  2860. See also function `simultaneous-find-file'.
  2861. If you want to keep the dired buffer displayed, type \\[split-window-vertically] first.
  2862. If you want just the marked files displayed and nothing else, type \\[delete-other-windows] first."
  2863.   (interactive "P")
  2864.   (dired-simultaneous-find-file (dired-get-marked-files nil arg)))
  2865.  
  2866. (defun dired-simultaneous-find-file (file-list)
  2867.   "Visit all files in FILE-LIST and display them simultaneously.
  2868.  
  2869. The current window is split across all files in FILE-LIST, as evenly
  2870. as possible.  Remaining lines go to the bottommost window.
  2871.  
  2872. The number of files that can be displayed this way is restricted by
  2873. the height of the current window and the variable `window-min-height'."
  2874.   ;; It is usually too clumsy to specify FILE-LIST interactively
  2875.   ;; unless via dired (dired-do-find-file).
  2876.   (let ((size (/ (window-height) (length file-list))))
  2877.     (or (<= window-min-height size)
  2878.     (error "Too many files to visit simultaneously"))
  2879.     (find-file (car file-list))
  2880.     (setq file-list (cdr file-list))
  2881.     (while file-list
  2882.       ;; Split off vertically a window of the desired size
  2883.       ;; The upper window will have SIZE lines.  We select the lower
  2884.       ;; (larger) window because we want to split that again.
  2885.       (select-window (split-window nil size))
  2886.       (let ((find-file-run-dired t))
  2887.         (find-file (car file-list)))
  2888.       (setq file-list (cdr file-list)))))
  2889.  
  2890. (defun dired-create-directory (directory)
  2891.   "Create a directory called DIRECTORY."
  2892.   (interactive
  2893.    (list (read-file-name "Create directory: "
  2894.              (dired-abbreviate-file-name
  2895.               (dired-current-directory)))))
  2896.   (let ((expanded (expand-file-name directory)))
  2897.     (make-directory expanded)
  2898.     ;; Because this function is meant to be called interactively, it moves
  2899.     ;; the point.
  2900.     (dired-goto-file expanded)))
  2901.  
  2902. (defun dired-recover-file ()
  2903.   "Recovers file from its autosave file.
  2904. If the file is an autosave file, then recovers its associated file instead."
  2905.   (interactive)
  2906.   (let* ((file (dired-get-filename))
  2907.      (name (file-name-nondirectory file))
  2908.      (asp (auto-save-file-name-p name))
  2909.      (orig (and
  2910.         asp
  2911.         (if (fboundp 'auto-save-original-name)
  2912.             (auto-save-original-name file)
  2913.           (error
  2914.            "Need auto-save package to compute original file name."))))
  2915.      (buff (if asp
  2916.            (and orig (get-file-buffer orig))
  2917.          (get-file-buffer file))))
  2918.     (and
  2919.      buff
  2920.      (buffer-modified-p buff)
  2921.      (or
  2922.       (yes-or-no-p
  2923.        (format
  2924.     "Recover file will erase the modified buffer %s.  Do it? "
  2925.     (buffer-name buff)))
  2926.       (error "Recover file aborted.")))
  2927.     (if asp
  2928.     (if orig
  2929.         (recover-file orig)
  2930.       (find-file file))
  2931.       (recover-file file))))
  2932.  
  2933.  
  2934. ;;;; --------------------------------------------------------------------
  2935. ;;;; Functions for extracting and manipulating file names
  2936. ;;;; --------------------------------------------------------------------
  2937.  
  2938. (defun dired-make-filename-string (filename &optional reverse)
  2939.   ;; Translates the way that a file name appears in a buffer, to
  2940.   ;; how it is used in a path name.  This is useful for non-unix
  2941.   ;; support in efs.
  2942.   filename)
  2943.  
  2944. (defun dired-get-filename (&optional localp no-error-if-not-filep)
  2945.   "In dired, return name of file mentioned on this line.
  2946. Value returned normally includes the directory name.
  2947. Optional arg LOCALP with value `no-dir' means don't include directory
  2948.   name in result.  A value of t means use path name relative to
  2949.   `default-directory', which still may contain slashes if in a subdirectory.
  2950. Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
  2951.   this line, otherwise an error occurs."
  2952.  
  2953.   ;; Compute bol & eol once, rather than twice inside move-to-filename
  2954.   ;; and move-to-end-of-filename
  2955.   (let ((eol (save-excursion (skip-chars-forward "^\n\r") (point)))
  2956.     (bol (save-excursion (skip-chars-backward "^\r\n") (point)))
  2957.     case-fold-search file p1 p2)
  2958.     (save-excursion
  2959.       (and
  2960.        (setq p1 (dired-move-to-filename (not no-error-if-not-filep) bol eol))
  2961.        (setq p2 (if (eq system-type 'windows-nt) ; ignore carriage-return at eol
  2962.             (1- (dired-move-to-end-of-filename no-error-if-not-filep bol eol))
  2963.           (dired-move-to-end-of-filename no-error-if-not-filep bol eol)))
  2964.        (setq file (buffer-substring p1 p2))
  2965.        ;; Check if ls quoted the names, and unquote them.
  2966.        ;; Using read to unquote is much faster than substituting
  2967.        ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
  2968.        (cond ((memq ?b dired-internal-switches) ; System V ls
  2969.           ;; This case is about 20% slower than without -b.
  2970.           (setq file
  2971.             (read
  2972.              (concat "\""
  2973.                    ;; some ls -b don't escape quotes, argh!
  2974.                  ;; This is not needed for GNU ls, though.
  2975.                  (or (dired-string-replace-match
  2976.                     "\\([^\\]\\)\"" file "\\1\\\\\"")
  2977.                  file)
  2978.                  "\""))))
  2979.            ;; If you do this, update dired-compatible-switches-p
  2980.          ;; ((memq ?Q dired-internal-switches) ; GNU ls
  2981.          ;;  (setq file (read file)))
  2982.            )))
  2983.     (and file
  2984.      (if (eq localp 'no-dir)
  2985.          (dired-make-filename-string file)
  2986.        (concat (dired-current-directory localp)
  2987.            (dired-make-filename-string file))))))
  2988.  
  2989. (defun dired-make-relative (file &optional dir no-error)
  2990.   ;; Convert FILE (an *absolute* pathname) to a pathname relative to DIR.
  2991.   ;; FILE must be absolute, or this function will return nonsense.
  2992.   ;; If FILE is not in a subdir of DIR, an error is signalled,
  2993.   ;; unless NO-ERROR is t. Then, ".."'s are inserted to give
  2994.   ;; a relative representation of FILE wrto DIR
  2995.   ;; eg.     FILE = /vol/tex/bin/foo DIR = /vol/local/bin/
  2996.   ;;         results in  ../../tex/bin/foo
  2997.   ;; DIR must be expanded.
  2998.   ;; DIR defaults to default-directory.
  2999.   ;; DIR must be file-name-as-directory, as with all directory args in
  3000.   ;; elisp code.
  3001.   (or dir (setq dir (expand-file-name default-directory)))
  3002.   (let ((flen (length file))
  3003.     (dlen (length dir)))
  3004.     (if (and (> flen dlen)
  3005.          (string-equal (substring file 0 dlen) dir))
  3006.     (substring file dlen)
  3007.       ;; Need to insert ..'s
  3008.       (or no-error (error  "%s: not in directory tree growing at %s" file dir))
  3009.       (if (string-equal file dir)
  3010.       "./"
  3011.     (let ((index 1)
  3012.           (count 0))
  3013.       (while (and (string-match "/" dir index)
  3014.               (<= (match-end 0) flen)
  3015.               (string-equal (substring file index (match-end 0))
  3016.                     (substring dir index (match-end 0))))
  3017.         (setq index (match-end 0)))
  3018.       (setq file (substring file index))
  3019.       (if (and (/= flen index)
  3020.            (not (string-match "/" file))
  3021.            (< flen dlen)
  3022.            (string-equal file (substring dir index flen))
  3023.            (= (aref dir flen) ?/))
  3024.           (setq file "."
  3025.             count -1))
  3026.       ;; count how many slashes remain in dir.
  3027.       (while (string-match "/" dir index)
  3028.         (setq index (match-end 0)
  3029.           count (1+ count)))
  3030.       (apply 'concat (nconc (make-list count "../") (list file))))))))
  3031.  
  3032. ;;; Functions for manipulating file names.
  3033. ;;
  3034. ;;  Used by file tranformers.
  3035. ;;  Define here rather than in dired-shell.el, as it wouldn't be
  3036. ;;  unreasonable to use these elsewhere.
  3037.  
  3038. (defun dired-file-name-base (fn)
  3039.   "Returns the base name of FN.
  3040. This is the file without directory part, and extension. See the variable
  3041. `dired-filename-re-ext'."
  3042.   (setq fn (file-name-nondirectory fn))
  3043.   (if (string-match dired-filename-re-ext fn 1)
  3044.       (substring fn 0 (match-beginning 0))
  3045.     fn))
  3046.  
  3047. (defun dired-file-name-extension (fn)
  3048.   "Returns the extension for file name FN.
  3049. See the variable dired-filename-re-ext'."
  3050.   (setq fn (file-name-nondirectory fn))
  3051.   (if (string-match dired-filename-re-ext fn 1)
  3052.       (substring fn (match-beginning 0))
  3053.     ""))
  3054.  
  3055. (defun dired-file-name-sans-rcs-extension (fn)
  3056.   "Returns the file name FN without its RCS extension \",v\"."
  3057.   (setq fn (file-name-nondirectory fn))
  3058.   (if (string-match ",v\\'" fn 1)
  3059.       (substring fn 0 (match-beginning 0))
  3060.     fn))
  3061.  
  3062. (defun dired-file-name-sans-compress-extension (fn)
  3063.   "Returns the file name FN without the extension from compress or gzip."
  3064.   (setq fn (file-name-nondirectory fn))
  3065.   (if (string-match "\\.\\([zZ]\\|gz\\)\\'" fn 1)
  3066.       (substring fn (match-beginning 0))
  3067.     fn))
  3068.  
  3069.  
  3070. ;;;; ---------------------------------------------------------------------
  3071. ;;;; Working with directory trees.
  3072. ;;;; ---------------------------------------------------------------------
  3073. ;;;
  3074. ;;;  This where code for the dired-subdir-alist is.
  3075.  
  3076. ;;; Utility functions for dired-subdir-alist
  3077.  
  3078. (defun dired-normalize-subdir (dir)
  3079.   ;; Prepend default-directory to DIR if relative path name.
  3080.   ;; dired-get-filename must be able to make a valid filename from a
  3081.   ;; file and its directory DIR.
  3082.   ;; Fully expand everything.
  3083.   (file-name-as-directory
  3084.    (if (file-name-absolute-p dir)
  3085.        (expand-file-name dir)
  3086.      (expand-file-name dir (expand-file-name default-directory)))))
  3087.  
  3088. (defun dired-get-subdir ()
  3089.   ;;"Return the subdir name on this line, or nil if not on a headerline."
  3090.   ;; Look up in the alist whether this is a headerline.
  3091.   (save-excursion
  3092.     (let ((cur-dir (dired-current-directory)))
  3093.       (beginning-of-line)        ; alist stores b-o-l positions
  3094.       (and (zerop (- (point)
  3095.              (dired-get-subdir-min (assoc cur-dir
  3096.                           dired-subdir-alist))))
  3097.        cur-dir))))
  3098.  
  3099. (defun dired-get-subdir-max (elt)
  3100.   ;; returns subdir max.
  3101.   (let ((pos (- (length dired-subdir-alist)
  3102.         (length (member elt dired-subdir-alist)))))
  3103.     (if (zerop pos)
  3104.     (point-max)
  3105.       (1- (dired-get-subdir-min (nth (1- pos) dired-subdir-alist))))))
  3106.  
  3107. (defun dired-clear-alist ()
  3108.   ;; Set all markers in dired-subdir-alist to nil.  Set the alist to nil too.
  3109.   (while dired-subdir-alist
  3110.     (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
  3111.     (setq dired-subdir-alist (cdr dired-subdir-alist))))
  3112.  
  3113. (defun dired-unsubdir (dir)
  3114.   ;; Remove DIR from the alist
  3115.   (setq dired-subdir-alist
  3116.     (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
  3117.  
  3118. (defun dired-simple-subdir-alist ()
  3119.   ;; Build and return `dired-subdir-alist' assuming just the top level
  3120.   ;; directory to be inserted.  Don't parse the buffer.
  3121.   (setq dired-subdir-alist
  3122.     (list (list (expand-file-name default-directory)
  3123.             (point-min-marker) dired-omit-files
  3124.             dired-internal-switches nil)))
  3125.   (if dired-verify-modtimes
  3126.       (dired-set-file-modtime (expand-file-name default-directory)
  3127.                   dired-subdir-alist)))
  3128.  
  3129. (defun dired-build-subdir-alist ()
  3130.   "Build `dired-subdir-alist' by parsing the buffer and return its new value."
  3131.   (interactive)
  3132.   (let ((o-alist dired-subdir-alist)
  3133.     (count 0)
  3134.     subdir)
  3135.     (dired-clear-alist)
  3136.     (save-excursion
  3137.       (goto-char (point-min))
  3138.       (while (re-search-forward dired-subdir-regexp nil t)
  3139.     (setq count (1+ count))
  3140.     (apply 'dired-alist-add-1
  3141.            (setq subdir (buffer-substring (match-beginning 2)
  3142.                           (match-end 2)))
  3143.            ;; Put subdir boundary between lines.
  3144.            (set-marker (make-marker) (match-end 1))
  3145.            (let ((elt (assoc subdir o-alist)))
  3146.          (if elt
  3147.              (list (nth 2 elt) (nth 3 elt))
  3148.            (list dired-omit-files dired-internal-switches)))))
  3149.       (if (interactive-p)
  3150.       (message "%d director%s." count (if (= 1 count) "y" "ies")))
  3151.       ;; We don't need to sort it because it is in buffer order per
  3152.       ;; constructionem.  Return new alist:
  3153.       ;; pointers for current-subdir may be stale
  3154.       dired-subdir-alist)))
  3155.  
  3156. (defun dired-alist-add (dir new-marker &optional omit switches)
  3157.   ;; Add new DIR at NEW-MARKER.  Sort alist.
  3158.   (dired-alist-add-1 dir new-marker omit switches)
  3159.   (dired-alist-sort))
  3160.  
  3161. (defun dired-alist-add-1 (dir new-marker &optional omit switches)
  3162.   ;; Add new DIR at NEW-MARKER.  Don't sort.
  3163.   (let ((dir (dired-normalize-subdir dir)))
  3164.     (setq dired-subdir-alist
  3165.       (cons (list dir new-marker omit switches nil) dired-subdir-alist))
  3166.     (if dired-verify-modtimes
  3167.     (dired-set-file-modtime dir dired-subdir-alist))))
  3168.  
  3169. (defun dired-alist-sort ()
  3170.   ;; Keep the alist sorted on buffer position.
  3171.   (setq dired-subdir-alist
  3172.     (sort dired-subdir-alist
  3173.           (function (lambda (elt1 elt2)
  3174.               (> (dired-get-subdir-min elt1)
  3175.                  (dired-get-subdir-min elt2)))))))
  3176.  
  3177. ;;; Utilities for working with subdirs in the dired buffer
  3178.  
  3179. ;; This function is the heart of tree dired.
  3180. ;; It is called for each retrieved filename.
  3181. ;; It could stand to be faster, though it's mostly function call
  3182. ;; overhead.  Avoiding to funcall seems to save about 10% in
  3183. ;; dired-get-filename.  Make it a defsubst?
  3184. (defun dired-current-directory (&optional localp)
  3185.   "Return the name of the subdirectory to which this line belongs.
  3186. This returns a string with trailing slash, like `default-directory'.
  3187. Optional argument means return a file name relative to `default-directory'.
  3188. In this it returns \"\" for the top directory."
  3189.   (let* ((here (point))
  3190.      (dir (catch 'done
  3191.         (mapcar (function
  3192.              (lambda (x)
  3193.                (if (<= (dired-get-subdir-min x) here)
  3194.                    (throw 'done (car x)))))
  3195.             dired-subdir-alist))))
  3196.     (if (listp dir) (error "dired-subdir-alist seems to be mangled"))
  3197.     (if localp
  3198.     (let ((def-dir (expand-file-name default-directory)))
  3199.       (if (string-equal dir def-dir)
  3200.           ""
  3201.         (dired-make-relative dir def-dir)))
  3202.       dir)))
  3203.  
  3204. ;; Subdirs start at the beginning of their header lines and end just
  3205. ;; before the beginning of the next header line (or end of buffer).
  3206.  
  3207. (defun dired-subdir-min ()
  3208.   ;; Returns the minimum position of the current subdir
  3209.   (save-excursion
  3210.     (if (not (dired-prev-subdir 0 t t))
  3211.     (error "Not in a subdir!")
  3212.       (point))))
  3213.  
  3214. (defun dired-subdir-max ()
  3215.   ;; Returns the maximum position of the current subdir
  3216.   (save-excursion
  3217.     (if (dired-next-subdir 1 t t)
  3218.     (1- (point)) ; Do not include separating empty line.
  3219.       (point-max))))
  3220.  
  3221.  
  3222. ;;;; --------------------------------------------------------
  3223. ;;;; Deleting files
  3224. ;;;; --------------------------------------------------------
  3225.  
  3226. (defun dired-flag-file-deletion (arg)
  3227.   "In dired, flag the current line's file for deletion.
  3228. With prefix arg, repeat over several lines.
  3229.  
  3230. If on a subdir headerline, mark all its files except `.' and `..'."
  3231.   (interactive "p")
  3232.   (dired-mark arg dired-del-marker))
  3233.  
  3234. (defun dired-flag-file-deletion-backup (arg)
  3235.   "Flag current file for deletion, and move to previous line.
  3236. With a prefix ARG, repeats this ARG times."
  3237.   (interactive "p")
  3238.   ;; Use dired-mark-file and not dired-mark, as this function
  3239.   ;; should do nothing special on subdir headers.
  3240.   (dired-mark-file (- arg) dired-del-marker))
  3241.  
  3242. (defun dired-flag-subdir-files ()
  3243.   "Flag all the files in the current subdirectory for deletion."
  3244.   (interactive)
  3245.   (dired-mark-subdir-files dired-del-marker))
  3246.  
  3247. (defun dired-unflag (arg)
  3248.   "In dired, remove a deletion flag from the current line's file.
  3249. Optional prefix ARG says how many lines to unflag."
  3250.   (interactive "p")
  3251.   (let (buffer-read-only)
  3252.     (dired-repeat-over-lines
  3253.      arg
  3254.      (function
  3255.       (lambda ()
  3256.     (if (char-equal (following-char) dired-del-marker)
  3257.         (progn
  3258.           (setq dired-del-flags-number (max (1- dired-del-flags-number) 0))
  3259.           (dired-substitute-marker (point) dired-del-marker ?\ )))))))
  3260.   (dired-update-mode-line-modified))
  3261.  
  3262. (defun dired-backup-unflag (arg)
  3263.   "In dired, move up lines and remove deletion flag there.
  3264. Optional prefix ARG says how many lines to unflag; default is one line."
  3265.   (interactive "p")
  3266.   (dired-unflag (- arg)))
  3267.  
  3268. (defun dired-update-marker-counters (char &optional remove)
  3269.   (or (memq char '(?\  ?\n ?\r))
  3270.       (let ((counter (cond
  3271.               ((char-equal char dired-del-marker)
  3272.                'dired-del-flags-number)
  3273.               ((char-equal char dired-marker-char)
  3274.                'dired-marks-number)
  3275.           ('dired-other-marks-number))))
  3276.     (if remove
  3277.         (set counter (max (1- (symbol-value counter)) 0))
  3278.       (set counter (1+ (symbol-value counter)))))))
  3279.  
  3280. (defun dired-update-mode-line-modified (&optional check)
  3281.   ;; Updates the value of mode-line-modified in dired.
  3282.   ;; Currently assumes that it's of the form "-%%-", where % sometimes
  3283.   ;; gets replaced by %.  Should allow some sort of config flag.
  3284.   ;; SET is t to set to -DD-, nil to set to -%%-, and 'check means
  3285.   ;; examine the buffer to find out.
  3286.   (if check
  3287.       (save-excursion
  3288.     (let (char)
  3289.       (goto-char (point-min))
  3290.       (setq dired-del-flags-number 0
  3291.         dired-marks-number 0
  3292.         dired-other-marks-number 0)
  3293.       (while (not (eobp))
  3294.         (setq char (following-char))
  3295.         (cond
  3296.          ((char-equal char dired-del-marker)
  3297.           (setq dired-del-flags-number (1+ dired-del-flags-number)))
  3298.          ((char-equal char dired-marker-char)
  3299.           (setq dired-marks-number (1+ dired-marks-number)))
  3300.          ((memq char '(?\  ?\n ?\r))
  3301.           nil)
  3302.          ((setq dired-other-marks-number (1+ dired-other-marks-number))))
  3303.         (forward-line 1)))))
  3304.   (setq mode-line-modified
  3305.     (format dired-mode-line-modified
  3306.         (if (zerop dired-del-flags-number)
  3307.             "--"
  3308.           (format "%d%c" dired-del-flags-number dired-del-marker))
  3309.         (if (zerop dired-marks-number)
  3310.             "--"
  3311.           (format "%d%c" dired-marks-number dired-marker-char))
  3312.         (if (zerop dired-other-marks-number)
  3313.             "-"
  3314.           (int-to-string dired-other-marks-number))))
  3315.   (set-buffer-modified-p (buffer-modified-p)))
  3316.  
  3317. (defun dired-do-deletions (&optional nomessage)
  3318.   (dired-expunge-deletions))
  3319.  
  3320. (defun dired-expunge-deletions ()
  3321.   "In dired, delete the files flagged for deletion."
  3322.   (interactive)
  3323.   (let ((files (let ((dired-marker-char dired-del-marker))
  3324.          (dired-map-over-marks (cons (dired-get-filename) (point))
  3325.                        t))))
  3326.     (if files
  3327.     (progn
  3328.       (dired-internal-do-deletions files nil dired-del-marker)
  3329.       ;; In case the point gets left somewhere strange -- hope that
  3330.       ;; this doesn't cause asynch troubles later.
  3331.       (beginning-of-line)
  3332.       (dired-goto-next-nontrivial-file)
  3333.       (dired-update-mode-line-modified t)) ; play safe, it's cheap
  3334.       (message "(No deletions requested)"))))
  3335.  
  3336. (defun dired-do-delete (&optional arg)
  3337.   "Delete all marked (or next ARG) files."
  3338.   ;; This is more consistent with the file marking feature than
  3339.   ;; dired-expunge-deletions.
  3340.   (interactive "P")
  3341.   (dired-internal-do-deletions
  3342.    ;; this may move point if ARG is an integer
  3343.    (dired-map-over-marks (cons (dired-get-filename) (point))
  3344.            arg)
  3345.    arg)
  3346.   (beginning-of-line)
  3347.   (dired-goto-next-nontrivial-file))
  3348.  
  3349. (defun dired-internal-do-deletions (l arg &optional marker-char)
  3350.   ;; L is an alist of files to delete, with their buffer positions.
  3351.   ;; ARG is the prefix arg.
  3352.   ;; Filenames are absolute (VMS needs this for logical search paths).
  3353.   ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
  3354.   ;; That way as changes are made in the buffer they do not shift the
  3355.   ;; lines still to be changed, so the (point) values in L stay valid.
  3356.   ;; Also, for subdirs in natural order, a subdir's files are deleted
  3357.   ;; before the subdir itself - the other way around would not work.
  3358.   (save-excursion
  3359.     (let ((files (mapcar (function car) l))
  3360.       (count (length l))
  3361.       (succ 0)
  3362.       (cdir (dired-current-directory))
  3363.       failures)
  3364.       ;; canonicalize file list for pop up
  3365.       (setq files (nreverse (mapcar (function
  3366.                      (lambda (fn)
  3367.                        (dired-make-relative fn cdir t)))
  3368.                     files)))
  3369.       (if (or (memq 'delete dired-no-confirm)
  3370.           (dired-mark-pop-up
  3371.            " *Files Flagged for Deletion*" 'delete files
  3372.            dired-deletion-confirmer
  3373.            (format "Delete %s "
  3374.                (dired-mark-prompt arg files marker-char))))
  3375.       (save-excursion
  3376.         ;; files better be in reverse order for this loop!
  3377.         (while l
  3378.           (goto-char (cdr (car l)))
  3379.           (condition-case err
  3380.           (let ((fn (car (car l))))
  3381.             ;; This test is equivalent to
  3382.             ;; (and (file-directory-p fn)
  3383.             ;;      (not (file-symlink-p fn)))
  3384.             ;; but more efficient
  3385.             (if (if (eq t (car (file-attributes fn)))
  3386.                 (if (<= (length (directory-files fn)) 2)
  3387.                 (progn (delete-directory fn) t)
  3388.                   (and (or
  3389.                     (memq 'recursive-delete dired-no-confirm)
  3390.                     (funcall
  3391.                      dired-deletion-confirmer
  3392.                      (format "\
  3393. Recursively delete directory and files within %s? "
  3394.                          (dired-make-relative fn))))
  3395.                    (progn
  3396.                      (dired-recursive-delete-directory fn)
  3397.                      t)))
  3398.               (progn (delete-file fn) t))
  3399.             (progn
  3400.               (setq succ (1+ succ))
  3401.               (message "%s of %s deletions" succ count)
  3402.               (dired-clean-up-after-deletion fn))))
  3403.         (error;; catch errors from failed deletions
  3404.          (dired-log (buffer-name (current-buffer)) "%s\n" err)
  3405.          (setq failures (cons (car (car l)) failures))))
  3406.           (setq l (cdr l)))))
  3407.       (if failures
  3408.       (dired-log-summary
  3409.        (buffer-name (current-buffer))
  3410.        (format "%d of %d deletion%s failed:" (length failures) count
  3411.            (dired-plural-s count))
  3412.        failures)
  3413.     (if (zerop succ)
  3414.         (message "(No deletions performed)")
  3415.       (message "%d deletion%s done" succ (dired-plural-s succ)))))))
  3416.  
  3417. (defun dired-recursive-delete-directory (fn)
  3418.   ;; Recursively deletes directory FN, and all of its contents.
  3419.        (let* ((fn (expand-file-name fn))
  3420.           (handler (find-file-name-handler
  3421.             fn 'dired-recursive-delete-directory)))
  3422.      (if handler
  3423.          (funcall handler 'dired-recursive-delete-directory fn)
  3424.        (progn
  3425.          (or (file-exists-p fn)
  3426.          (signal
  3427.           'file-error
  3428.           (list "Removing old file name" "no such directory" fn)))
  3429.          ;; Which is better, -r or -R?
  3430.          (call-process "rm" nil nil nil "-r" (directory-file-name fn))
  3431.          (and (file-exists-p fn)
  3432.           (error "Failed to recusively delete %s" fn))))))
  3433.  
  3434. (defun dired-clean-up-after-deletion (fn)
  3435.   ;; Offer to kill buffer of deleted file FN.
  3436.   (let ((buf (get-file-buffer fn)))
  3437.     (and buf
  3438.      (or (memq 'kill-file-buffer dired-no-confirm)
  3439.          (funcall (function yes-or-no-p)
  3440.               (format "Kill buffer of %s, too? "
  3441.                   (file-name-nondirectory fn))))
  3442.      (save-excursion ; you never know where kill-buffer leaves you
  3443.        (kill-buffer buf)))))
  3444.  
  3445. ;;; Cleaning a directory -- flagging backups for deletion
  3446.  
  3447. (defun dired-clean-directory (keep &optional marker msg)
  3448.   "Flag numerical backups for deletion.
  3449. Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
  3450. Positive prefix arg KEEP overrides `dired-kept-versions';
  3451. Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
  3452.  
  3453. To clear the flags on these files, you can use \\[dired-flag-backup-files]
  3454. with a prefix argument."
  3455.   (interactive "P")
  3456.   (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
  3457.   (let* ((early-retention (if (< keep 0) (- keep) kept-old-versions))
  3458.      (late-retention (if (<= keep 0) dired-kept-versions keep))
  3459.      (msg (or msg
  3460.           (format
  3461.            "Cleaning numerical backups (keeping %d late, %d old)"
  3462.            late-retention early-retention)))
  3463.      (trample-marker (or marker dired-del-marker))
  3464.      (file-version-assoc-list))
  3465.     (message "%s..." msg)
  3466.     ;; Do this after messaging, as it may take a while.
  3467.     (setq file-version-assoc-list (dired-collect-file-versions))
  3468.     ;; Sort each VERSION-NUMBER-LIST,
  3469.     ;; and remove the versions to be deleted.
  3470.     (let ((fval file-version-assoc-list))
  3471.       (while fval
  3472.     (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
  3473.            (v-count (length sorted-v-list)))
  3474.       (if (> v-count (+ early-retention late-retention))
  3475.           (rplacd (nthcdr early-retention sorted-v-list)
  3476.               (nthcdr (- v-count late-retention)
  3477.                   sorted-v-list)))
  3478.       (rplacd (car fval)
  3479.           (cdr sorted-v-list)))
  3480.     (setq fval (cdr fval))))
  3481.     ;; Look at each file.  If it is a numeric backup file,
  3482.     ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
  3483.     (dired-map-dired-file-lines (function
  3484.                  (lambda (fn)
  3485.                    (dired-trample-file-versions
  3486.                     fn file-version-assoc-list
  3487.                     trample-marker))))
  3488.     (message "%s...done" msg)))
  3489.  
  3490. (defun dired-collect-file-versions ()
  3491.   ;; If it looks like a file has versions, return a list of the versions.
  3492.   ;; The return value is ((FILENAME . (VERSION1 VERSION2 ...)) ...)
  3493.   (let (result)
  3494.     (dired-map-dired-file-lines
  3495.      (function
  3496.       (lambda (fn)
  3497.     (let* ((base-versions
  3498.         (concat (file-name-nondirectory fn) ".~"))
  3499.            (bv-length (length base-versions))
  3500.            (possibilities (file-name-all-completions
  3501.                    base-versions
  3502.                    (file-name-directory fn))))
  3503.       (if possibilities
  3504.           (setq result (cons (cons fn
  3505.                        (mapcar 'backup-extract-version
  3506.                            possibilities)) result)))))))
  3507.     result))
  3508.  
  3509. (defun dired-trample-file-versions (fn alist marker)
  3510.   ;; ALIST is an alist of filenames and versions used to determine
  3511.   ;; if each file should be flagged for deletion.
  3512.   ;; This version using file-name-sans-versions is probably a lot slower
  3513.   ;; than Sebastian's original, but it is more easily adaptable to non-unix.
  3514.   (let ((base (file-name-sans-versions fn))
  3515.     base-version-list bv-length)
  3516.     (and (not (string-equal base fn))
  3517.      (setq base-version-list (assoc base alist))
  3518.      (setq bv-length (string-match "[0-9]" fn (length base)))
  3519.      (not (memq (backup-extract-version fn) base-version-list))
  3520.      (progn (skip-chars-backward "^\n\r")
  3521.         (bolp)) ; make sure the preceding char isn't \r.
  3522.      (dired-substitute-marker (point) (following-char) marker))))
  3523.  
  3524. (defun dired-map-dired-file-lines (fun)
  3525.   ;; Perform FUN with point at the end of each non-directory line.
  3526.   ;; FUN takes one argument, the filename (complete pathname).
  3527.   (dired-check-ls-l)
  3528.   (save-excursion
  3529.     (let (file buffer-read-only)
  3530.       (goto-char (point-min))
  3531.       (while (not (eobp))
  3532.     (save-excursion
  3533.       (and (not (and dired-re-dir (looking-at dired-re-dir)))
  3534.            (not (memq (following-char) '(?\n ?\n)))
  3535.            (setq file (dired-get-filename nil t)) ; nil on non-file
  3536.            (progn (skip-chars-forward "^\n\r")
  3537.               (funcall fun file))))
  3538.     (forward-line 1)))))            ; this guarantees that we don't
  3539.                     ; operate on omitted files.
  3540.  
  3541.  
  3542. ;;;; -----------------------------------------------------------
  3543. ;;;; Confirmations and prompting the user.
  3544. ;;;; -----------------------------------------------------------
  3545.  
  3546. (defun dired-plural-s (count)
  3547.   (if (= 1 count) "" "s"))
  3548.  
  3549. (defun dired-mark-prompt (arg files &optional marker-char)
  3550.   ;; Return a string for use in a prompt, either the current file
  3551.   ;; name, or the marker and a count of marked files.
  3552.   (let ((count (length files)))
  3553.     (if (= count 1)
  3554.     (car files)
  3555.       ;; more than 1 file:
  3556.       (if (integerp arg)
  3557.       (cond ((zerop arg) "[no files]")
  3558.         ((> arg 0) "[following]")
  3559.         ((< arg 0) "[preceding]"))
  3560.     (char-to-string (or marker-char dired-marker-char))))))
  3561.  
  3562. (defun dired-pop-to-buffer (buf)
  3563.   ;; Pop up buffer BUF.
  3564.   ;; Make its window fit its contents.
  3565.   (let ((window (selected-window))
  3566.     target-lines w2)
  3567.     (cond ;; if split-window-threshold is enabled, use the largest window
  3568.      ((and (> (window-height (setq w2 (get-largest-window)))
  3569.           split-height-threshold)
  3570.        (= (frame-width) (window-width w2)))
  3571.       (setq window w2))
  3572.      ;; if the least-recently-used window is big enough, use it
  3573.      ((and (> (window-height (setq w2 (get-lru-window)))
  3574.           (* 2 window-min-height))
  3575.        (= (frame-width) (window-width w2)))
  3576.       (setq window w2)))
  3577.     (save-excursion
  3578.       (set-buffer buf)
  3579.       (goto-char (point-max))
  3580.       (skip-chars-backward "\n\r\t ")
  3581.       (setq target-lines (count-lines (point-min) (point)))
  3582.       ;; Don't forget to count the last line.
  3583.       (if (not (bolp))
  3584.       (setq target-lines (1+ target-lines))))
  3585.     (if (<= (window-height window) (* 2 window-min-height))
  3586.     ;; At this point, every window on the frame is too small to split.
  3587.     (setq w2 (display-buffer buf))
  3588.       (setq w2 (split-window
  3589.         window
  3590.         (max window-min-height
  3591.              (- (window-height window)
  3592.             (1+ (max window-min-height target-lines)))))))
  3593.     (set-window-buffer w2 buf)
  3594.     (if (< (1- (window-height w2)) target-lines)
  3595.     (progn
  3596.       (select-window w2)
  3597.       (enlarge-window (- target-lines (1- (window-height w2))))))
  3598.     (set-window-start w2 1)))
  3599.  
  3600. (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
  3601.   ;; Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
  3602.   ;; Return FUNCTION's result on ARGS after popping up a window (in a buffer
  3603.   ;; named BUFNAME, nil gives \" *Marked Files*\") showing the marked
  3604.   ;; files.  Uses function `dired-pop-to-buffer' to do that.
  3605.   ;; FUNCTION should not manipulate files.
  3606.   ;; It should only read input (an argument or confirmation).
  3607.   ;; The window is not shown if there is just one file or
  3608.   ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
  3609.   ;; FILES is the list of marked files.
  3610.   (if (memq op-symbol dired-no-confirm)
  3611.       (apply function args)
  3612.     (or bufname (setq bufname  " *Marked Files*"))
  3613.     (if (<= (length files) 1)
  3614.     (apply function args)
  3615.       (save-excursion
  3616.     (let ((standard-output (set-buffer (get-buffer-create bufname))))
  3617.       (erase-buffer)
  3618.       (dired-format-columns-of-files files)
  3619.       (dired-remove-text-properties (point-min) (point-max))
  3620.       (setq mode-line-format (format "       %s  [%d files]"
  3621.                      bufname (length files)))))
  3622.       (save-window-excursion
  3623.     (dired-pop-to-buffer bufname)
  3624.     (apply function args)))))
  3625.  
  3626. (defun dired-column-widths (columns list &optional across)
  3627.   ;; Returns the column widths for breaking LIST into
  3628.   ;; COLUMNS number of columns.
  3629.   (cond
  3630.    ((null list)
  3631.     nil)
  3632.    ((= columns 1)
  3633.     (list (apply 'max (mapcar 'length list))))
  3634.    ((let* ((len (length list))
  3635.        (col-length (/ len columns))
  3636.        (remainder (% len columns))
  3637.        (i 0)
  3638.        (j 0)
  3639.        (max-width 0)
  3640.        widths padding)
  3641.       (if (zerop remainder)
  3642.       (setq padding 0)
  3643.     (setq col-length (1+ col-length)
  3644.           padding (- columns remainder)))
  3645.       (setq list (nconc (copy-sequence list) (make-list padding nil)))
  3646.       (setcdr (nthcdr (1- (+ len padding)) list) list)
  3647.       (while (< i columns)
  3648.     (while (< j col-length)
  3649.       (setq max-width (max max-width (length (car list)))
  3650.         list (if across (nthcdr columns list) (cdr list))
  3651.         j (1+ j)))
  3652.     (setq widths (cons (+ max-width 2) widths)
  3653.           max-width 0
  3654.           j 0
  3655.           i (1+ i))
  3656.     (if across (setq list (cdr list))))
  3657.       (setcar widths (- (car widths) 2))
  3658.       (nreverse widths)))))
  3659.   
  3660. (defun dired-calculate-columns (list &optional across)
  3661.   ;; Returns a list of integers which are the column widths that best pack
  3662.   ;; LIST, a list of strings, onto the screen.
  3663.   (and list
  3664.        (let* ((width (1- (window-width)))
  3665.           (columns (max 1 (/ width
  3666.                  (+ 2 (apply 'max (mapcar 'length list))))))
  3667.           col-list last-col-list)
  3668.      (while (<= (apply '+ (setq col-list
  3669.                     (dired-column-widths columns list across)))
  3670.             width)
  3671.        (setq columns (1+ columns)
  3672.          last-col-list col-list))
  3673.      (or last-col-list col-list))))
  3674.  
  3675. (defun dired-format-columns-of-files (files &optional across)
  3676.   ;; Returns the number of lines used.
  3677.   ;; If ACROSS is non-nil, sorts across rather than down the buffer, like
  3678.   ;; ls -x
  3679.   (and files
  3680.        (let* ((columns (dired-calculate-columns files across))
  3681.           (ncols (length columns))
  3682.           (ncols1 (1- ncols))
  3683.           (nfiles (length files))
  3684.           (nrows (+ (/ nfiles ncols)
  3685.             (if (zerop (% nfiles ncols)) 0 1)))
  3686.           (space-left (- (window-width) (apply '+ columns) 1))
  3687.           (i 0)
  3688.           (j 0)
  3689.           file padding stretch float-stretch)
  3690.      (if (zerop ncols1)
  3691.          (setq stretch 0
  3692.            float-stretch 0)
  3693.        (setq stretch (/ space-left ncols1)
  3694.          float-stretch (% space-left ncols1)))
  3695.      (setq files (nconc (copy-sequence files) ; fill up with empty fns
  3696.                 (make-list (- (* ncols nrows) nfiles) "")))
  3697.      (setcdr (nthcdr (1- (length files)) files) files) ; make circular
  3698.      (while (< j nrows)
  3699.        (while (< i ncols)
  3700.          (princ (setq file (car files)))
  3701.          (setq padding (- (nth i columns) (length file)))
  3702.          (or (= i ncols1)
  3703.          (progn
  3704.            (setq padding (+ padding stretch))
  3705.            (if (< i float-stretch) (setq padding (1+ padding)))))
  3706.          (princ (make-string padding ?\ ))
  3707.          (setq files (if across (cdr files) (nthcdr nrows files))
  3708.            i (1+ i)))
  3709.        (princ "\n")
  3710.        (setq i 0
  3711.          j (1+ j))
  3712.        (or across (setq files (cdr files))))
  3713.      nrows)))
  3714.  
  3715. (defun dired-query (qs-var qs-prompt &rest qs-args)
  3716.   ;; Query user and return nil or t.
  3717.   ;; Store answer in symbol VAR (which must initially be bound to nil).
  3718.   ;; Format PROMPT with ARGS.
  3719.   ;; Binding variable help-form will help the user who types C-h.
  3720.   (let* ((char (symbol-value qs-var))
  3721.      (action (cdr (assoc char dired-query-alist))))
  3722.     (cond ((eq 'yes action)
  3723.        t)                ; accept, and don't ask again
  3724.       ((eq 'no action)
  3725.        nil)                ; skip, and don't ask again
  3726.       (t;; no lasting effects from last time we asked - ask now
  3727.        (let ((qprompt (concat qs-prompt
  3728.                   (if help-form
  3729.                       (format " [yn!q or %s] "
  3730.                           (key-description
  3731.                            (char-to-string help-char)))
  3732.                     " [ynq or !] ")))
  3733.          (dired-in-query t)
  3734.          elt)
  3735.          ;; Actually it looks nicer without cursor-in-echo-area - you can
  3736.          ;; look at the dired buffer instead of at the prompt to decide.
  3737.          (apply 'message qprompt qs-args)
  3738.          (setq char (set qs-var (read-char)))
  3739.          (while (not (setq elt (assoc char dired-query-alist)))
  3740.            (message "Invalid char - type %c for help." help-char)
  3741.            (ding)
  3742.            (sit-for 1)
  3743.            (apply 'message qprompt qs-args)
  3744.            (setq char (set qs-var (read-char))))
  3745.          (memq (cdr elt) '(t y yes)))))))
  3746.  
  3747. (defun dired-mark-confirm (op-symbol operation arg)
  3748.   ;; Request confirmation from the user that the operation described
  3749.   ;; by OP-SYMBOL is to be performed on the marked files.
  3750.   ;; Confirmation consists in a y-or-n question with a file list
  3751.   ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
  3752.   ;; OPERATION is a string describing the operation. Used for prompting
  3753.   ;; the user.
  3754.   ;; The files used are determined by ARG (like in dired-get-marked-files).
  3755.   (or (memq op-symbol dired-no-confirm)
  3756.       (let ((files (dired-get-marked-files t arg)))
  3757.     (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
  3758.                (concat  operation " "
  3759.                     (dired-mark-prompt arg files) "? ")))))
  3760.  
  3761. (defun dired-mark-read-file-name (prompt dir op-symbol arg files)
  3762.   (dired-mark-pop-up
  3763.    nil op-symbol files
  3764.    (function read-file-name)
  3765.    (format prompt (dired-mark-prompt arg files)) dir))
  3766.  
  3767. (defun dired-mark-read-string (prompt initial op-symbol arg files
  3768.                       &optional history-sym)
  3769.   ;; Reading arguments with history.
  3770.   ;; Read arguments for a mark command of type OP-SYMBOL,
  3771.   ;; perhaps popping up the list of marked files.
  3772.   ;; ARG is the prefix arg and indicates whether the files came from
  3773.   ;; marks (ARG=nil) or a repeat factor (integerp ARG).
  3774.   ;; If the current file was used, the list has but one element and ARG
  3775.   ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
  3776.   ;; PROMPT for a string, with INITIAL input.
  3777.   (dired-mark-pop-up
  3778.    nil op-symbol files
  3779.    (function
  3780.     (lambda (prompt initial)
  3781.       (let ((hist (or history-sym
  3782.               (cdr (assq op-symbol dired-op-history-alist))
  3783.               'dired-history)))
  3784.     (dired-read-with-history prompt initial hist))))
  3785.    (format prompt (dired-mark-prompt arg files)) initial))
  3786.  
  3787.  
  3788. ;;;; ----------------------------------------------------------
  3789. ;;;; Marking files.
  3790. ;;;; ----------------------------------------------------------
  3791.  
  3792. (defun dired-mark (arg &optional char)
  3793.   "Mark the current (or next ARG) files.
  3794. If on a subdir headerline, mark all its files except `.' and `..'.
  3795.  
  3796. Use \\[dired-unmark-all-files] to remove all marks,
  3797. and \\[dired-unmark] to remove the mark of the current file."
  3798.   (interactive "p")
  3799.   (if (dired-get-subdir)
  3800.       (dired-mark-subdir-files char)
  3801.     (dired-mark-file arg char)))
  3802.  
  3803. (defun dired-mark-file (arg &optional char)
  3804.   "Mark ARG files starting from the current file line.
  3805. Optional CHAR indicates a marker character to use."
  3806.   (let (buffer-read-only)
  3807.     (if (memq (or char dired-marker-char) '(?\  ?\n ?\r))
  3808.     (error "Invalid marker character %c" dired-marker-char))
  3809.     (or char (setq char dired-marker-char))
  3810.     (dired-repeat-over-lines
  3811.      arg
  3812.      (function
  3813.       (lambda ()
  3814.     (dired-update-marker-counters (following-char) t)
  3815.     (dired-substitute-marker (point) (following-char) char)
  3816.     (dired-update-marker-counters char))))
  3817.     (dired-update-mode-line-modified)))
  3818.  
  3819. (defun dired-mark-subdir-files (&optional char)
  3820.   "Mark all files except `.' and `..'."
  3821.   (interactive)
  3822.   (save-excursion
  3823.     (dired-mark-files-in-region (dired-subdir-min) (dired-subdir-max) char)))
  3824.  
  3825. (defun dired-unmark (arg)
  3826.   "Unmark the current (or next ARG) files.
  3827. If looking at a subdir, unmark all its files except `.' and `..'."
  3828.   (interactive "p")
  3829.   (let (buffer-read-only)
  3830.     (dired-repeat-over-lines
  3831.      arg
  3832.      (function
  3833.       (lambda ()
  3834.     (let ((char (following-char)))
  3835.       (or (memq char '(?\  ?\n ?\r))
  3836.           (progn
  3837.         (cond
  3838.          ((char-equal char dired-marker-char)
  3839.           (setq dired-marks-number (max (1- dired-marks-number) 0)))
  3840.          ((char-equal char dired-del-marker)
  3841.           (setq dired-del-flags-number
  3842.             (max (1- dired-del-flags-number) 0)))
  3843.          ((setq dired-other-marks-number
  3844.             (max (1- dired-other-marks-number) 0))))
  3845.         (dired-substitute-marker (point) char ?\ )))))))
  3846.     (dired-update-mode-line-modified)))
  3847.  
  3848. (defun dired-mark-prefix (&optional arg)
  3849.   "Mark the next ARG files with the next character typed.
  3850. If ARG is negative, marks the previous files."
  3851.   (interactive "p")
  3852.   (if (sit-for echo-keystrokes)
  3853.       (cond
  3854.        ((or (= arg 1) (zerop arg))
  3855.     (message "Mark with character?"))
  3856.        ((< arg 0)
  3857.     (message "Mark %d file%s moving backwards?"
  3858.          (- arg) (dired-plural-s (- arg))))
  3859.        ((> arg 1)
  3860.     (message "Mark %d following files with character?" arg))))
  3861.   (dired-mark arg (read-char)))
  3862.  
  3863. (defun dired-change-marks (old new)
  3864.   "Change all OLD marks to NEW marks.
  3865. OLD and NEW are both characters used to mark files.
  3866. With a prefix, prompts for a mark to toggle. In other words, all unmarked
  3867. files receive that mark, and all files currently marked with that mark become
  3868. unmarked."
  3869.   ;; When used in a lisp program, setting NEW to nil means toggle the mark OLD.
  3870.   (interactive
  3871.    (let* ((cursor-in-echo-area t)
  3872.       (old nil)
  3873.       (new nil)
  3874.       (markers (dired-mark-list))
  3875.       (default (cond ((null markers)
  3876.               (error "No markers in buffer"))
  3877.              ((= (length markers) 1)
  3878.               (setq old (car markers)))
  3879.              ((memq dired-marker-char markers)
  3880.               dired-marker-char)
  3881.              ;; picks the last one in the buffer. reasonable?
  3882.              ((car markers)))))
  3883.      (or old (setq old
  3884.            (progn
  3885.              (if current-prefix-arg
  3886.              (message "Toggle mark (default %c): " default)
  3887.                (message "Change old mark (default %c): " default))
  3888.              (read-char))))
  3889.      (if (memq old '(?\  ?\n ?\r)) (setq old default))
  3890.      (or current-prefix-arg
  3891.      (setq new (progn
  3892.              (message
  3893.               "Change %c marks to new mark (RET means abort): " old)
  3894.              (read-char))))
  3895.      (list old new)))
  3896.   (let ((old-count  (cond
  3897.              ((char-equal old dired-marker-char)
  3898.               'dired-marks-number)
  3899.              ((char-equal old dired-del-marker)
  3900.               'dired-del-flags-number)
  3901.              ('dired-other-marks-number))))
  3902.     (if new
  3903.     (or (memq new '(?\  ?\n ?\r))
  3904.         ;; \n and \r aren't valid marker chars. Assume that if the
  3905.         ;; user hits return, he meant to abort the command.
  3906.         (let ((string (format "\n%c" old))
  3907.           (new-count  (cond
  3908.                    ((char-equal new dired-marker-char)
  3909.                 'dired-marks-number)
  3910.                    ((char-equal new dired-del-marker)
  3911.                 'dired-del-flags-number)
  3912.                    ('dired-other-marks-number)))
  3913.           (buffer-read-only nil))
  3914.           (save-excursion
  3915.         (goto-char (point-min))
  3916.         (while (search-forward string nil t)
  3917.           (if (char-equal (preceding-char) old)
  3918.               (progn
  3919.             (dired-substitute-marker (1- (point)) old new)
  3920.             (set new-count (1+ (symbol-value new-count)))
  3921.             (set old-count (max (1- (symbol-value old-count)) 0))))
  3922.           ))))
  3923.       (save-excursion
  3924.     (let ((ucount 0)
  3925.           (mcount 0)
  3926.           (buffer-read-only nil))
  3927.       (goto-char (point-min))
  3928.       (while (not (eobp))
  3929.         (or (dired-between-files)
  3930.         (looking-at dired-re-dot)
  3931.         (cond
  3932.          ((= (following-char) ?\ )
  3933.           (setq mcount (1+ mcount))
  3934.           (set old-count (1+ (symbol-value old-count)))
  3935.           (dired-substitute-marker (point) ?\  old))
  3936.          ((= (following-char) old)
  3937.           (setq ucount (1+ ucount))
  3938.           (set old-count (max (1- (symbol-value old-count)) 0))
  3939.           (dired-substitute-marker (point) old ?\ ))))
  3940.         (forward-line 1))
  3941.       (message "Unmarked %d file%s; marked %d file%s with %c."
  3942.            ucount (dired-plural-s ucount) mcount
  3943.            (dired-plural-s mcount) old)))))
  3944.   (dired-update-mode-line-modified))
  3945.  
  3946. (defun dired-unmark-all-files (flag &optional arg)
  3947.   "Remove a specific mark or any mark from every file.
  3948. With prefix arg, query for each marked file.
  3949. Type \\[help-command] at that time for help.
  3950. With a zero prefix, only counts the number of marks."
  3951.   (interactive
  3952.    (let* ((cursor-in-echo-area t)
  3953.       executing-kbd-macro) ; for XEmacs
  3954.      (list (and (not (eq current-prefix-arg 0))
  3955.         (progn (message "Remove marks (RET means all): ") (read-char)))
  3956.        current-prefix-arg)))
  3957.   (save-excursion
  3958.     (let* ((help-form "\
  3959. Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
  3960. `!' to unflag all remaining files with no more questions.")
  3961.        (allp (memq flag '(?\n ?\r)))
  3962.        (count-p (eq arg 0))
  3963.        (count (if (or allp count-p)
  3964.               (mapcar
  3965.                (function
  3966.             (lambda (elt)
  3967.             (cons elt 0)))
  3968.                (nreverse (dired-mark-list)))
  3969.             0))
  3970.        (msg "")
  3971.        (no-query (or (not arg) count-p))
  3972.        buffer-read-only case-fold-search query)
  3973.       (goto-char (point-min))
  3974.       (if (or allp count-p)
  3975.       (while (re-search-forward dired-re-mark nil t)
  3976.         (if (or no-query
  3977.             (dired-query 'query "Unmark file `%s'? "
  3978.                  (dired-get-filename t)))
  3979.         (let ((ent (assq (preceding-char) count)))
  3980.           (if ent (setcdr ent (1+ (cdr ent))))
  3981.           (or count-p (dired-substitute-marker
  3982.                    (- (point) 1) (preceding-char) ?\ ))))
  3983.         (forward-line 1))
  3984.     (while (search-forward (format "\n%c" flag) nil t)
  3985.       (if (or no-query
  3986.           (dired-query 'query "Unmark file `%s'? "
  3987.                    (dired-get-filename t)))
  3988.           (progn
  3989.         (dired-substitute-marker (match-beginning 0) flag ?\ )
  3990.         (setq count (1+ count))))))
  3991.       (if (or allp count-p)
  3992.       (mapcar
  3993.        (function
  3994.         (lambda (elt)
  3995.           (or (zerop (cdr elt))
  3996.           (setq msg (format "%s%s%d %c%s"
  3997.                     msg
  3998.                     (if (zerop (length msg))
  3999.                     " "
  4000.                       ", ")
  4001.                     (cdr elt)
  4002.                     (car elt)
  4003.                     (if (= 1 (cdr elt)) "" "'s"))))))
  4004.        count)
  4005.     (or (zerop count)
  4006.         (setq msg (format " %d %c%s"
  4007.                   count flag (if (= 1 count) "" "'s")))))
  4008.       (if (zerop (length msg))
  4009.       (setq msg " none")
  4010.     (or count-p (dired-update-mode-line-modified t)))
  4011.       (message "%s:%s" (if count-p "Number of marks" "Marks removed") msg))))
  4012.  
  4013. (defun dired-get-marked-files (&optional localp arg)
  4014.   "Return the marked files' names as list of strings.
  4015. The list is in the same order as the buffer, that is, the car is the
  4016.   first marked file.
  4017. Values returned are normally absolute pathnames.
  4018. Optional arg LOCALP as in `dired-get-filename'.
  4019. Optional second argument ARG forces to use other files.  If ARG is an
  4020.   integer, use the next ARG files.  If ARG is otherwise non-nil, use
  4021.   current file.  Usually ARG comes from the current prefix arg."
  4022.   (save-excursion
  4023.     (nreverse (dired-map-over-marks (dired-get-filename localp) arg))))
  4024.  
  4025. ;;; Utility functions for marking files
  4026.  
  4027. (defun dired-mark-files-in-region (start end &optional char)
  4028.   (let (buffer-read-only)
  4029.     (if (> start end)
  4030.     (error "start > end"))
  4031.     (goto-char start)            ; assumed at beginning of line
  4032.     (or char (setq char dired-marker-char))
  4033.     (while (< (point) end)
  4034.       ;; Skip subdir line and following garbage like the `total' line:
  4035.       (while (and (< (point) end) (dired-between-files))
  4036.     (forward-line 1))
  4037.       (if (and (/= (following-char) char)
  4038.            (not (looking-at dired-re-dot))
  4039.            (save-excursion
  4040.          (dired-move-to-filename nil (point))))
  4041.       (progn
  4042.         (dired-update-marker-counters (following-char) t)
  4043.         (dired-substitute-marker (point) (following-char) char)
  4044.         (dired-update-marker-counters char)))
  4045.       (forward-line 1)))
  4046.   (dired-update-mode-line-modified))
  4047.  
  4048. (defun dired-mark-list ()
  4049.   ;; Returns a list of all marks currently used in the buffer.
  4050.   (let ((result nil)
  4051.     char)
  4052.     (save-excursion
  4053.       (goto-char (point-min))
  4054.       (while (not (eobp))
  4055.     (and (not (memq (setq char (following-char)) '(?\  ?\n ?\r)))
  4056.          (not (memq char result))
  4057.          (setq result (cons char result)))
  4058.     (forward-line 1)))
  4059.     result))
  4060.  
  4061. ;;; Dynamic markers
  4062.  
  4063. (defun dired-set-current-marker-string ()
  4064.   "Computes and returns `dired-marker-string'."
  4065.   (prog1
  4066.       (setq dired-marker-string
  4067.         (if dired-marker-stack
  4068.         (let* ((n (+ (length dired-marker-stack) 5))
  4069.                (str (make-string n ?\ ))
  4070.                (list dired-marker-stack)
  4071.                (pointer dired-marker-stack-pointer))
  4072.           (setq n (1- n))
  4073.           (aset str n ?\])
  4074.           (setq n (1- n))
  4075.           (while list
  4076.             (aset str n (car list))
  4077.             (if (zerop pointer)
  4078.             (progn
  4079.               (setq n (1- n))
  4080.               (aset str n dired-marker-stack-cursor)))
  4081.             (setq n (1- n)
  4082.               pointer (1- pointer)
  4083.               list (cdr list)))
  4084.           (aset str n dired-default-marker)
  4085.           (if (zerop pointer)
  4086.               (aset str 2 dired-marker-stack-cursor))
  4087.           (aset str 1 ?\[)
  4088.           str)
  4089.           ""))
  4090.     (set-buffer-modified-p (buffer-modified-p))))
  4091.  
  4092. (defun dired-set-marker-char (c)
  4093.   "Set the marker character to something else.
  4094. Use \\[dired-restore-marker-char] to restore the previous value."
  4095.   (interactive "cNew marker character: ")
  4096.   (and (memq c '(?\  ?\n ?\r)) (error "invalid marker char %c" c))
  4097.   (setq dired-marker-stack (cons c dired-marker-stack)
  4098.     dired-marker-stack-pointer 0
  4099.     dired-marker-char c)
  4100.   (dired-update-mode-line-modified t)
  4101.   (dired-set-current-marker-string))
  4102.  
  4103. (defun dired-restore-marker-char ()
  4104.   "Restore the marker character to its previous value.
  4105. Uses `dired-default-marker' if the marker stack is empty."
  4106.   (interactive)
  4107.   (setq dired-marker-stack (cdr dired-marker-stack)
  4108.     dired-marker-char (car dired-marker-stack)
  4109.     dired-marker-stack-pointer (min dired-marker-stack-pointer
  4110.                     (length dired-marker-stack)))
  4111.   (or dired-marker-char
  4112.       (setq dired-marker-char dired-default-marker))
  4113.   (dired-set-current-marker-string)
  4114.   (dired-update-mode-line-modified t)
  4115.   (or dired-marker-stack (message "Marker is %c" dired-marker-char)))
  4116.  
  4117. (defun dired-marker-stack-left (n)
  4118.   "Moves the marker stack cursor to the left."
  4119.   (interactive "p")
  4120.   (let ((len (1+ (length dired-marker-stack))))
  4121.     (or dired-marker-stack (error "Dired marker stack is empty."))
  4122.     (setq dired-marker-stack-pointer
  4123.       (% (+ dired-marker-stack-pointer n) len))
  4124.     (if (< dired-marker-stack-pointer 0)
  4125.     (setq dired-marker-stack-pointer (+ dired-marker-stack-pointer
  4126.                         len)))
  4127.     (dired-set-current-marker-string)
  4128.     (setq dired-marker-char
  4129.       (if (= dired-marker-stack-pointer (1- len))
  4130.           dired-default-marker
  4131.         (nth dired-marker-stack-pointer dired-marker-stack))))
  4132.   (dired-update-mode-line-modified t))
  4133.  
  4134. (defun dired-marker-stack-right (n)
  4135.   "Moves the marker stack cursor to the right."
  4136.   (interactive "p")
  4137.   (dired-marker-stack-left (- n)))
  4138.  
  4139. ;;; Commands to mark or flag files based on their characteristics or names.
  4140.  
  4141. (defun dired-mark-symlinks (&optional unflag-p)
  4142.   "Mark all symbolic links.
  4143. With prefix argument, unflag all those files."
  4144.   (interactive "P")
  4145.   (dired-check-ls-l)
  4146.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  4147.     (dired-mark-if (looking-at dired-re-sym) "symbolic link"))
  4148.   (dired-update-mode-line-modified t))
  4149.  
  4150. (defun dired-mark-directories (&optional unflag-p)
  4151.   "Mark all directory file lines except `.' and `..'.
  4152. With prefix argument, unflag all those files."
  4153.   (interactive "P")
  4154.   (if dired-re-dir
  4155.       (progn
  4156.     (dired-check-ls-l)
  4157.     (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  4158.       (dired-mark-if (and (looking-at dired-re-dir)
  4159.                   (not (looking-at dired-re-dot)))
  4160.              "directory file"))))
  4161.   (dired-update-mode-line-modified t))
  4162.  
  4163. (defun dired-mark-executables (&optional unflag-p)
  4164.   "Mark all executable files.
  4165. With prefix argument, unflag all those files."
  4166.   (interactive "P")
  4167.   (if dired-re-exe
  4168.       (progn
  4169.     (dired-check-ls-l)
  4170.     (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  4171.       (dired-mark-if (looking-at dired-re-exe) "executable file"))))
  4172.   (dired-update-mode-line-modified t))
  4173.     
  4174. (defun dired-flag-backup-files (&optional unflag-p)
  4175.   "Flag all backup files (names ending with `~') for deletion.
  4176. With prefix argument, unflag these files."
  4177.   (interactive "P")
  4178.   (dired-check-ls-l)
  4179.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  4180.     (dired-mark-if
  4181.      (and (not (and dired-re-dir (looking-at dired-re-dir)))
  4182.       (let ((fn (dired-get-filename t t)))
  4183.         (if fn (backup-file-name-p fn))))
  4184.      "backup file"))
  4185.   (dired-update-mode-line-modified t))
  4186.  
  4187. (defun dired-flag-auto-save-files (&optional unflag-p)
  4188.   "Flag for deletion files whose names suggest they are auto save files.
  4189. A prefix argument says to unflag those files instead."
  4190.   (interactive "P")
  4191.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  4192.     (dired-mark-if
  4193.      ;; It is less than general to check for ~ here,
  4194.      ;; but it's the only way this runs fast enough.
  4195.      (and (save-excursion (end-of-line)
  4196.               (eq (preceding-char) ?#))
  4197.       (not (and dired-re-dir (looking-at dired-re-dir)))
  4198.       (let ((fn (dired-get-filename t t)))
  4199.         (if fn (auto-save-file-name-p
  4200.             (file-name-nondirectory fn)))))
  4201.      "auto save file"))
  4202.   (dired-update-mode-line-modified t))
  4203.  
  4204. (defun dired-mark-rcs-files (&optional unflag-p)
  4205.   "Mark all files that are under RCS control.
  4206. With prefix argument, unflag all those files.
  4207. Mentions RCS files for which a working file was not found in this buffer.
  4208. Type \\[dired-why] to see them again."
  4209.   ;; Returns failures, or nil on success.
  4210.   ;; Finding those with locks would require to peek into the ,v file,
  4211.   ;; depends slightly on the RCS version used and should be done
  4212.   ;; together with the Emacs RCS interface.
  4213.   ;; Unfortunately, there is no definitive RCS interface yet.
  4214.   (interactive "P")
  4215.   (message "%sarking RCS controlled files..." (if unflag-p "Unm" "M"))
  4216.   (let ((dired-marker-char (if unflag-p ?\  dired-marker-char))
  4217.     rcs-files wf failures count total)
  4218.     (mapcar                ; loop over subdirs
  4219.      (function
  4220.       (lambda (dir)
  4221.     (or (equal (file-name-nondirectory (directory-file-name dir))
  4222.            "RCS")
  4223.         ;; skip inserted RCS subdirs
  4224.         (setq rcs-files
  4225.           (append (directory-files dir t ",v\\'") ; *,v and RCS/*,v
  4226.               (let ((rcs-dir (expand-file-name "RCS" dir)))
  4227.                 (if (file-directory-p rcs-dir)
  4228.                 (mapcar    ; working files from ./RCS are in ./
  4229.                  (function
  4230.                   (lambda (x)
  4231.                     (expand-file-name x dir)))
  4232.                  (directory-files
  4233.                   (file-name-as-directory rcs-dir)
  4234.                   nil ",v\\'"))))
  4235.               rcs-files)))))
  4236.      (mapcar (function car) dired-subdir-alist))
  4237.     (setq total (length rcs-files))
  4238.     (while rcs-files
  4239.       (setq wf (substring (car rcs-files) 0 -2)
  4240.         rcs-files (cdr rcs-files))
  4241.       (save-excursion (if (dired-goto-file wf)
  4242.               (dired-mark 1) ; giving a prefix avoids checking
  4243.                      ; for subdir line.
  4244.             (setq failures (cons wf failures)))))
  4245.     (dired-update-mode-line-modified t)
  4246.     (if (null failures)
  4247.     (message "%d RCS file%s %smarked."
  4248.          total (dired-plural-s total) (if unflag-p "un" ""))
  4249.       (setq count (length failures))
  4250.       (dired-log-summary (buffer-name (current-buffer))
  4251.              "RCS working file not found %s" failures)
  4252.       (message "%d RCS file%s: %d %smarked - %d not found %s."
  4253.            total (dired-plural-s total) (- total count)
  4254.            (if unflag-p "un" "") count failures))
  4255.     failures))
  4256.  
  4257.  
  4258. ;;;; ------------------------------------------------------------
  4259. ;;;; Logging failures
  4260. ;;;; ------------------------------------------------------------
  4261.  
  4262. (defun dired-why ()
  4263.   "Pop up a buffer with error log output from Dired.
  4264. A group of errors from a single command ends with a formfeed.
  4265. Thus, use \\[backward-page] to find the beginning of a group of errors."
  4266.   (interactive)
  4267.   (if (get-buffer dired-log-buffer)
  4268.       (let ((owindow (selected-window))
  4269.         (window (display-buffer (get-buffer dired-log-buffer))))
  4270.     (unwind-protect
  4271.         (progn
  4272.           (select-window window)
  4273.           (goto-char (point-max))
  4274.           (recenter -1))
  4275.       (select-window owindow)))))
  4276.  
  4277. (defun dired-log (buffer-name log &rest args)
  4278.   ;; Log a message or the contents of a buffer.
  4279.   ;; BUFFER-NAME is the name of the dired buffer to which the message applies.
  4280.   ;; If LOG is a string and there are more args, it is formatted with
  4281.   ;; those ARGS.  Usually the LOG string ends with a \n.
  4282.   ;; End each bunch of errors with (dired-log t): this inserts
  4283.   ;; current time and buffer, and a \f (formfeed).
  4284.   (or (stringp buffer-name) (setq buffer-name (buffer-name buffer-name)))
  4285.   (let ((obuf (current-buffer)))
  4286.     (unwind-protect            ; want to move point
  4287.     (progn
  4288.       (set-buffer (get-buffer-create dired-log-buffer))
  4289.       (goto-char (point-max))
  4290.       (let (buffer-read-only)
  4291.         (cond ((stringp log)
  4292.            (insert (if args
  4293.                    (apply (function format) log args)
  4294.                  log)))
  4295.           ((bufferp log)
  4296.            (insert-buffer log))
  4297.           ((eq t log)
  4298.            (insert "\n\t" (current-time-string)
  4299.                "\tBuffer `" buffer-name "'\n\f\n")))))
  4300.       (set-buffer obuf))))
  4301.  
  4302. (defun dired-log-summary (buffer-name string failures)
  4303.   (message (if failures "%s--type y for details %s"
  4304.          "%s--type y for details")
  4305.        string failures)
  4306.   ;; Log a summary describing a bunch of errors.
  4307.   (dired-log buffer-name (concat "\n" string))
  4308.   (if failures (dired-log buffer-name "\n%s" failures))
  4309.   (dired-log buffer-name t))
  4310.  
  4311.  
  4312. ;;;; -------------------------------------------------------
  4313. ;;;; Sort mode of dired buffers.
  4314. ;;;; -------------------------------------------------------
  4315.  
  4316. (defun dired-sort-type (list)
  4317.   ;; Returns the sort type of LIST, as a symbol.
  4318.   (let* ((list (reverse list))
  4319.      (alist (sort
  4320.          (mapcar (function
  4321.               (lambda (x)
  4322.                 (cons (length (memq (car x) list)) (cdr x))))
  4323.              dired-sort-type-alist)
  4324.          (function
  4325.           (lambda (x y)
  4326.             (> (car x) (car y))))))
  4327.      (winner (car alist)))
  4328.     (if (zerop (car winner))
  4329.     'name
  4330.       (cdr winner))))
  4331.  
  4332. (defun dired-sort-set-modeline (&optional switches)
  4333.   ;; Set modeline display according to dired-internal-switches.
  4334.   ;; Modeline display of "by name" or "by date" guarantees the user a
  4335.   ;; match with the corresponding regexps.  Non-matching switches are
  4336.   ;; shown literally.
  4337.   (or switches (setq switches dired-internal-switches))
  4338.   (setq dired-sort-mode
  4339.     (if dired-show-ls-switches
  4340.         (concat " " (dired-make-switches-string
  4341.              (or switches dired-internal-switches)))
  4342.       (concat " by " (and (memq ?r switches) "rev-")
  4343.           (symbol-name (dired-sort-type switches)))))
  4344.   ;; update mode line
  4345.   (set-buffer-modified-p (buffer-modified-p)))
  4346.  
  4347. (defun dired-sort-toggle-or-edit (&optional arg)
  4348.   "Toggle between sort by date/name for the current subdirectory.
  4349.  
  4350. With a 0 prefix argument, simply reports on the current switches.
  4351.  
  4352. With a prefix 1 allows the ls switches for the current subdirectory to be 
  4353. edited.
  4354.  
  4355. With a prefix 2 allows the default ls switches for newly inserted
  4356. subdirectories to be edited. 
  4357.  
  4358. With a prefix \\[universal-argument] allows you to sort the entire
  4359. buffer by either name or date.
  4360.  
  4361. With a prefix \\[universal-argument] \\[universal-argument] allows the default switches
  4362. for the entire buffer to be edited, and then reverts the buffer so that all
  4363. subdirectories are sorted according to these switches.
  4364.  
  4365. Note that although dired allows different ls switches to be used for 
  4366. different subdirectories, certain combinations of ls switches are incompatible.
  4367. If incompatible switches are detected, dired will offer to revert the buffer
  4368. to force the ls switches for all subdirectories to a single value.  If you
  4369. refuse to revert the buffer, any change of ls switches will be aborted."
  4370.   (interactive "P")
  4371.   (cond
  4372.    ((eq arg 0)
  4373.     ;; Report on switches
  4374.     (message "Switches for current subdir: %s.  Default for buffer: %s."
  4375.          (dired-make-switches-string
  4376.           (nth 3 (assoc (dired-current-directory) dired-subdir-alist)))
  4377.           (dired-make-switches-string dired-internal-switches)))
  4378.    ((null arg)
  4379.     ;; Toggle between sort by date/name.
  4380.     (let* ((dir (dired-current-directory))
  4381.        (curr (nth 3 (assoc dir dired-subdir-alist))))
  4382.       (dired-sort-other
  4383.        (if (eq (dired-sort-type curr) 'name)
  4384.        (cons ?t curr)
  4385.      (mapcar (function
  4386.           (lambda (x)
  4387.             (setq curr
  4388.               (delq (car x) curr))))
  4389.          dired-sort-type-alist)
  4390.      curr)
  4391.        nil dir)))
  4392.    ((eq arg 1)
  4393.     ;; Edit switches for current subdir.
  4394.     (let* ((dir (dired-current-directory))
  4395.        (switch-string
  4396.         (read-string
  4397.          "New ls switches for current subdir (must contain -l): "
  4398.          (dired-make-switches-string
  4399.           (nth 3 (assoc dir dired-subdir-alist)))))
  4400.        (switches (dired-make-switches-list switch-string)))
  4401.       (if (dired-compatible-switches-p switches dired-internal-switches)
  4402.       (dired-sort-other switches nil dir)
  4403.     (if (or
  4404.          (memq 'sort-revert dired-no-confirm)
  4405.          (y-or-n-p
  4406.           (format
  4407.            "Switches %s incompatible with default %s.  Revert buffer? "
  4408.              switch-string
  4409.          (dired-make-switches-string dired-internal-switches))))
  4410.         (dired-sort-other switches nil nil)
  4411.       (error "Switches unchanged.  Remain as %s." switch-string)))))
  4412.    ((eq arg 2)
  4413.     ;; Set new defaults for subdirs inserted in the future.
  4414.     (let* ((switch-string
  4415.         (read-string
  4416.          "Default ls switches for new subdirs (must contain -l): "
  4417.          (dired-make-switches-string dired-internal-switches)))
  4418.        (switches (dired-make-switches-list switch-string))
  4419.        (alist dired-subdir-alist)
  4420.        x bad-switches)
  4421.       (while alist
  4422.     (setq x (nth 3 (car alist))
  4423.           alist (cdr alist))
  4424.     (or (dired-compatible-switches-p x switches)
  4425.         (member x bad-switches)
  4426.         (setq bad-switches (cons x bad-switches))))
  4427.       (if bad-switches
  4428.       (if (or (memq 'sort-revert dired-no-confirm)
  4429.           (y-or-n-p
  4430.            (format
  4431.             "Switches %s incompatible with %s.  Revert buffer? "
  4432.             switch-string (mapconcat 'dired-make-switches-string
  4433.                           bad-switches ", "))))
  4434.           (dired-sort-other switches nil nil)
  4435.         (error "Default switches unchanged.  Remain as %s."
  4436.            (dired-make-switches-string dired-internal-switches)))
  4437.     (dired-sort-other switches t nil))))
  4438.    ((or (equal arg '(4)) (eq arg 'date) (eq arg 'name))
  4439.     ;; Toggle the entire buffer name/data.
  4440.     (let ((cursor-in-echo-area t)
  4441.       (switches (copy-sequence dired-internal-switches))
  4442.       (type (and (symbolp arg) arg))
  4443.       char)
  4444.       (while (null type)
  4445.     (message "Sort entire buffer according to (n)ame or (d)ate? ")
  4446.     (setq char (read-char)
  4447.           type (cond
  4448.             ((char-equal char ?d) 'date)
  4449.             ((char-equal char ?n) 'name)
  4450.             (t (message "Type one of n or d.") (sit-for 1) nil))))
  4451.       (mapcar (function
  4452.            (lambda (x)
  4453.          (setq switches
  4454.                (delq (car x) switches))))
  4455.           dired-sort-type-alist)
  4456.       (dired-sort-other
  4457.        (if (eq type 'date) (cons ?t switches) switches) nil nil)))
  4458.    ((equal arg '(16))
  4459.     ;; Edit the switches for the entire buffer.
  4460.     (dired-sort-other
  4461.      (dired-make-switches-list
  4462.       (read-string
  4463.        "Change ls switches for entire buffer to (must contain -l): "
  4464.        (dired-make-switches-string dired-internal-switches)))
  4465.      nil nil))
  4466.    (t
  4467.     ;; No idea what's going on.
  4468.     (error
  4469.      "Invalid prefix.  See %s dired-sort-toggle-or-edit."
  4470.      (substitute-command-keys
  4471.       (if (featurep 'ehelp)
  4472.       "\\[electric-describe-function]"
  4473.     "\\[describe-function]"))))))
  4474.  
  4475. (defun dired-sort-other (switches &optional no-revert subdir)
  4476.   ;; Specify new ls SWITCHES for current dired buffer.
  4477.   ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
  4478.   ;; If subdir is non-nil, only changes the switches for the
  4479.   ;; sudirectory.
  4480.   (if subdir
  4481.       (let ((elt (assoc subdir dired-subdir-alist)))
  4482.     (if elt (setcar (nthcdr 3 elt) switches)))
  4483.     (setq dired-internal-switches switches))
  4484.   (or no-revert
  4485.       (cond
  4486.        
  4487.        (subdir
  4488.     (let ((ofile (dired-get-filename nil t))
  4489.           (opoint (point)))
  4490.       (message "Relisting %s..." subdir)
  4491.       (dired-insert-subdir subdir switches)
  4492.       (message "Relisting %s... done" subdir)
  4493.       (or (and ofile (dired-goto-file ofile)) (goto-char opoint))))
  4494.        
  4495.        ((memq ?R switches)
  4496.     ;; We are replacing a buffer with a giant recursive listing.
  4497.     (let ((opoint (point))
  4498.           (ofile (dired-get-filename nil t))
  4499.           (hidden-subdirs (dired-remember-hidden))
  4500.           (mark-alist (dired-remember-marks (point-min) (point-max)))
  4501.           (kill-files-p (save-excursion
  4502.                   (goto-char (point))
  4503.                   (search-forward
  4504.                    (concat (char-to-string ?\r)
  4505.                        (regexp-quote
  4506.                     (char-to-string
  4507.                      dired-kill-marker-char)))
  4508.                    nil t)))
  4509.           (omit-files (nth 2 (nth (1- (length dired-subdir-alist))
  4510.                       dired-subdir-alist)))
  4511.           buffer-read-only)
  4512.       (dired-readin dired-directory (current-buffer)
  4513.             (or (consp dired-directory)
  4514.                 (null (file-directory-p dired-directory))))
  4515.       (dired-mark-remembered mark-alist)    ; mark files that were marked
  4516.       (if kill-files-p (dired-do-hide dired-kill-marker-char))
  4517.       (if omit-files
  4518.           (dired-omit-expunge nil t))
  4519.       ;; hide subdirs that were hidden
  4520.       (save-excursion
  4521.         (mapcar (function (lambda (dir)
  4522.                 (if (dired-goto-subdir dir)
  4523.                     (dired-hide-subdir 1))))
  4524.             hidden-subdirs))
  4525.       ;; Try to get back to where we were
  4526.       (or (and ofile (dired-goto-file ofile))
  4527.           (goto-char opoint))
  4528.       (dired-move-to-filename)))
  4529.        
  4530.        (t
  4531.     ;; Clear all switches in the subdir alist
  4532.     (setq dired-subdir-alist
  4533.           (mapcar (function
  4534.                (lambda (x)
  4535.              (setcar (nthcdr 3 x) nil)
  4536.              x))
  4537.               dired-subdir-alist))
  4538.     (revert-buffer nil t))))
  4539.   (dired-update-mode-line t))
  4540.  
  4541. (defun dired-compatible-switches-p (list1 list2)
  4542.   ;; Returns t if list1 and list2 are allowed as switches in the same
  4543.   ;; dired buffer.
  4544.   (and (eq (null (or (memq ?l list1) (memq ?o list1) (memq ?g list1)))
  4545.        (null (or (memq ?l list2) (memq ?o list2) (memq ?g list2))))
  4546.        (eq (null (memq ?F list1)) (null (memq ?F list2)))
  4547.        (eq (null (memq ?p list1)) (null (memq ?p list2)))
  4548.        (eq (null (memq ?b list1)) (null (memq ?b list2)))))
  4549.  
  4550. (defun dired-check-ls-l (&optional switches)
  4551.   ;; Check for long-style listings
  4552.   (let ((switches (or switches dired-internal-switches)))
  4553.     (or (memq ?l switches) (memq ?o switches) (memq ?g switches)
  4554.     (error "Dired needs -l, -o, or -g in ls switches"))))
  4555.  
  4556.  
  4557. ;;;; --------------------------------------------------------------
  4558. ;;;; Creating new files.
  4559. ;;;; --------------------------------------------------------------
  4560. ;;;
  4561. ;;;  The dired-create-files paradigm is used for copying, renaming,
  4562. ;;;  compressing, and making hard and soft links.
  4563.  
  4564. (defun dired-file-marker (file)
  4565.   ;; Return FILE's marker, or nil if unmarked.
  4566.   (save-excursion
  4567.     (and (dired-goto-file file)
  4568.      (progn
  4569.        (skip-chars-backward "^\n\r")
  4570.        (and (not (= ?\040 (following-char)))
  4571.         (following-char))))))
  4572.  
  4573. ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
  4574. (defun dired-create-files (file-creator operation fn-list name-constructor
  4575.                     &optional marker-char query
  4576.                     implicit-to)
  4577.   ;; Create a new file for each from a list of existing files.  The user
  4578.   ;; is queried, dired buffers are updated, and at the end a success or
  4579.   ;; failure message is displayed
  4580.   
  4581.   ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
  4582.   ;; It is called for each file and must create newfile, the entry of
  4583.   ;; which will be added.  The user will be queried if the file already
  4584.   ;; exists.  If oldfile is removed by FILE-CREATOR (i.e, it is a
  4585.   ;; rename), it is FILE-CREATOR's responsibility to update dired
  4586.   ;; buffers.  FILE-CREATOR must abort by signalling a file-error if it
  4587.   ;; could not create newfile.  The error is caught and logged.
  4588.   
  4589.   ;; OPERATION (a capitalized string, e.g. `Copy') describes the
  4590.   ;; operation performed.  It is used for error logging.
  4591.   
  4592.   ;; FN-LIST is the list of files to copy (full absolute pathnames).
  4593.   
  4594.   ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
  4595.   ;; skip.  If it skips files, it is supposed to tell why (using dired-log).
  4596.  
  4597.   ;; Optional MARKER-CHAR is a character with which to mark every
  4598.   ;; newfile's entry, or t to use the current marker character if the
  4599.   ;; oldfile was marked.
  4600.  
  4601.   ;; QUERY is a function to use to prompt the user about creating a file.
  4602.   ;; It accepts two  args, the from and to files,
  4603.   ;; and must return nil or t. If QUERY is nil, then no user
  4604.   ;; confirmation will be requested.
  4605.  
  4606.   ;; If IMPLICIT-TO is non-nil, then the file constructor does not take
  4607.   ;; a to-file arg. e.g. compress.
  4608.  
  4609.   (let ((success-count 0)
  4610.     (total (length fn-list))
  4611.     failures skipped overwrite-query)
  4612.     ;; Fluid vars used for storing responses of previous queries must be
  4613.     ;; initialized.
  4614.     (dired-save-excursion
  4615.       (setq dired-overwrite-backup-query nil
  4616.         dired-file-creator-query nil)
  4617.       (mapcar
  4618.        (function
  4619.     (lambda (from)
  4620.       (let ((to (funcall name-constructor from)))
  4621.         (if to
  4622.         (if (equal to from)
  4623.             (progn
  4624.               (dired-log (buffer-name (current-buffer))
  4625.                  "Cannot %s to same file: %s\n"
  4626.                  (downcase operation) from)
  4627.               (setq skipped (cons (dired-make-relative from) skipped)))
  4628.           (if (or (null query)
  4629.               (funcall query from to))
  4630.               (let* ((overwrite (let (jka-compr-enabled)
  4631.                       ;; Don't let jka-compr fool us.
  4632.                       (file-exists-p to)))
  4633.                  ;; for dired-handle-overwrite
  4634.                  (dired-overwrite-confirmed 
  4635.                   (and overwrite
  4636.                    (let ((help-form '(format "\
  4637. Type SPC or `y' to overwrite file `%s',
  4638. DEL or `n' to skip to next,
  4639. ESC or `q' to not overwrite any of the remaining files,
  4640. `!' to overwrite all remaining files with no more questions." to)))
  4641.                      (dired-query 'overwrite-query
  4642.                           "Overwrite %s?" to))))
  4643.                  ;; must determine if FROM is marked before
  4644.                  ;; file-creator gets a chance to delete it
  4645.                  ;; (in case of a move).
  4646.                  (actual-marker-char
  4647.                   (cond  ((characterp marker-char) marker-char)
  4648.                      (marker-char (dired-file-marker from))
  4649.                      (t nil))))
  4650.             (if (and overwrite (null dired-overwrite-confirmed))
  4651.                 (setq skipped (cons (dired-make-relative from)
  4652.                         skipped))
  4653.               (condition-case err
  4654.                   (let ((dired-unhandle-add-files
  4655.                      (cons to dired-unhandle-add-files)))
  4656.                 (if implicit-to
  4657.                     (funcall file-creator from
  4658.                          dired-overwrite-confirmed)
  4659.                   (funcall file-creator from to
  4660.                        dired-overwrite-confirmed))
  4661.                 (setq success-count (1+ success-count))
  4662.                 (message "%s: %d of %d"
  4663.                      operation success-count total)
  4664.                 (dired-add-file to actual-marker-char))
  4665.                 (file-error        ; FILE-CREATOR aborted
  4666.                  (progn
  4667.                    (setq failures (cons (dired-make-relative from)
  4668.                             failures))
  4669.                    (dired-log (buffer-name (current-buffer))
  4670.                       "%s `%s' to `%s' failed:\n%s\n"
  4671.                       operation from to err))))))
  4672.             (setq skipped (cons (dired-make-relative from) skipped))))
  4673.           (setq skipped (cons (dired-make-relative from) skipped))))))
  4674.        fn-list)
  4675.       (cond
  4676.        (failures
  4677.     (dired-log-summary
  4678.      (buffer-name (current-buffer))
  4679.      (format "%s failed for %d of %d file%s"
  4680.          operation (length failures) total
  4681.          (dired-plural-s total)) failures))
  4682.        (skipped
  4683.     (dired-log-summary
  4684.      (buffer-name (current-buffer))
  4685.      (format "%s: %d of %d file%s skipped"
  4686.          operation (length skipped) total
  4687.          (dired-plural-s total)) skipped))
  4688.        (t
  4689.     (message "%s: %s file%s."
  4690.          operation success-count (dired-plural-s success-count)))))))
  4691.   
  4692. (defun dired-do-create-files (op-symbol file-creator operation arg
  4693.                          &optional marker-char
  4694.                          prompter how-to)
  4695.   ;; Create a new file for each marked file.
  4696.   ;; Prompts user for target, which is a directory in which to create
  4697.   ;;   the new files.  Target may be a plain file if only one marked
  4698.   ;;   file exists.
  4699.   ;; OP-SYMBOL is the symbol for the operation.  Function `dired-mark-pop-up'
  4700.   ;;   will determine wether pop-ups are appropriate for this OP-SYMBOL.
  4701.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  4702.   ;; ARG as in dired-get-marked-files.
  4703.   ;; PROMPTER is a function of one-arg, the list of files, to return a prompt
  4704.   ;;     to use for dired-read-file-name. If it is nil, then a default prompt
  4705.   ;;     will be used.
  4706.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  4707.   ;; Optional arg HOW-TO determines how to treat target:
  4708.   ;;   If HOW-TO is not given (or nil), and target is a directory, the
  4709.   ;;     file(s) are created inside the target directory.  If target
  4710.   ;;     is not a directory, there must be exactly one marked file,
  4711.   ;;     else error.
  4712.   ;;   If HOW-TO is t, then target is not modified.  There must be
  4713.   ;;     exactly one marked file, else error.
  4714.   ;; Else HOW-TO is assumed to be a function of one argument, target,
  4715.   ;;     that looks at target and returns a value for the into-dir
  4716.   ;;     variable.  The function dired-into-dir-with-symlinks is provided
  4717.   ;;     for the case (common when creating symlinks) that symbolic
  4718.   ;;     links to directories are not to be considered as directories
  4719.   ;;     (as file-directory-p would if HOW-TO had been nil).
  4720.  
  4721.   (let* ((fn-list (dired-get-marked-files nil arg))
  4722.      (fn-count (length fn-list))
  4723.      (cdir (dired-current-directory))
  4724.      (target (expand-file-name
  4725.            (dired-mark-read-file-name
  4726.             (if prompter
  4727.             (funcall prompter fn-list)
  4728.               (concat operation " %s to: "))
  4729.             (dired-dwim-target-directory)
  4730.             op-symbol arg (mapcar (function
  4731.                        (lambda (fn)
  4732.                          (dired-make-relative fn cdir t)))
  4733.                       fn-list))))
  4734.      (into-dir (cond ((null how-to) (file-directory-p target))
  4735.              ((eq how-to t) nil)
  4736.              (t (funcall how-to target)))))
  4737.     (if (and (> fn-count 1)
  4738.          (not into-dir))
  4739.     (error "Marked %s: target must be a directory: %s" operation target))
  4740.     ;; rename-file bombs when moving directories unless we do this:
  4741.     (or into-dir (setq target (directory-file-name target)))
  4742.     (dired-create-files
  4743.      file-creator operation fn-list
  4744.      (if into-dir            ; target is a directory
  4745.      (list 'lambda '(from)
  4746.            (list 'expand-file-name '(file-name-nondirectory from) target))
  4747.        (list 'lambda '(from) target))
  4748.      marker-char)))
  4749.  
  4750. (defun dired-into-dir-with-symlinks (target)
  4751.   (and (file-directory-p target)
  4752.        (not (file-symlink-p target))))
  4753. ;; This may not always be what you want, especially if target is your
  4754. ;; home directory and it happens to be a symbolic link, as is often the
  4755. ;; case with NFS and automounters.  Or if you want to make symlinks
  4756. ;; into directories that themselves are only symlinks, also quite
  4757. ;; common.
  4758. ;; So we don't use this function as value for HOW-TO in
  4759. ;; dired-do-symlink, which has the minor disadvantage of
  4760. ;; making links *into* a symlinked-dir, when you really wanted to
  4761. ;; *overwrite* that symlink.  In that (rare, I guess) case, you'll
  4762. ;; just have to remove that symlink by hand before making your marked
  4763. ;; symlinks.
  4764.  
  4765. (defun dired-handle-overwrite (to)
  4766.   ;; Save old version of a to be overwritten file TO.
  4767.   ;; `dired-overwrite-confirmed' and `dired-overwrite-backup-query'
  4768.   ;; are fluid vars from dired-create-files.
  4769.   (if (and dired-backup-if-overwrite
  4770.        dired-overwrite-confirmed
  4771.        (or (eq 'always dired-backup-if-overwrite)
  4772.            (dired-query 'dired-overwrite-backup-query
  4773.             (format "Make backup for existing file `%s'? " to))))
  4774.       (let ((backup (car (find-backup-file-name to))))
  4775.     (rename-file to backup 0))))    ; confirm overwrite of old backup
  4776.  
  4777. (defun dired-dwim-target-directory ()
  4778.   ;; Try to guess which target directory the user may want.
  4779.   ;; If there is a dired buffer displayed in the next window, use
  4780.   ;; its current subdir, else use current subdir of this dired buffer.
  4781.   ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
  4782.   (let* ((this-dir (and (eq major-mode 'dired-mode)
  4783.             (dired-current-directory)))
  4784.      (dwimmed
  4785.       (if dired-dwim-target
  4786.           (let* ((other-buf (window-buffer (next-window)))
  4787.              (other-dir (save-excursion
  4788.                   (set-buffer other-buf)
  4789.                   (and (eq major-mode 'dired-mode)
  4790.                        (dired-current-directory)))))
  4791.         (or other-dir this-dir))
  4792.         this-dir)))
  4793.     (and dwimmed (dired-abbreviate-file-name dwimmed))))
  4794.  
  4795. (defun dired-get-target-directory ()
  4796.   "Writes a copy of the current subdirectory into an active minibuffer."
  4797.   (interactive)
  4798.   (let ((mb (dired-get-active-minibuffer-window)))
  4799.     (if mb
  4800.     (let ((dir (dired-current-directory)))
  4801.       (select-window mb)
  4802.       (set-buffer (window-buffer mb))
  4803.       (erase-buffer)
  4804.       (insert dir))
  4805.       (error "No active minibuffer"))))
  4806.  
  4807. ;;; Copying files
  4808.  
  4809. (defun dired-do-copy (&optional arg)
  4810.   "Copy all marked (or next ARG) files, or copy the current file.
  4811. When operating on just the current file, you specify the new name.
  4812. When operating on multiple or marked files, you specify a directory
  4813. and the files are copied into that directory, retaining the same file names.
  4814.  
  4815. A zero prefix argument copies nothing.  But it toggles the
  4816. variable `dired-copy-preserve-time' (which see)."
  4817.   (interactive "P")
  4818.   (if (not (zerop (prefix-numeric-value arg)))
  4819.       (dired-do-create-files 'copy (function dired-copy-file)
  4820.                    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  4821.                    arg dired-keep-marker-copy)
  4822.     (setq dired-copy-preserve-time (not dired-copy-preserve-time))
  4823.     (if dired-copy-preserve-time
  4824.     (message "Copy will preserve time.")
  4825.       (message "Copied files will get current date."))))
  4826.  
  4827. (defun dired-copy-file (from to ok-flag)
  4828.   (dired-handle-overwrite to)
  4829.   (copy-file from to ok-flag dired-copy-preserve-time))
  4830.  
  4831. ;;; Renaming/moving files
  4832.  
  4833. (defun dired-do-rename (&optional arg)
  4834.   "Rename current file or all marked (or next ARG) files.
  4835. When renaming just the current file, you specify the new name.
  4836. When renaming multiple or marked files, you specify a directory.
  4837.  
  4838. A zero ARG moves no files but toggles `dired-dwim-target' (which see)."
  4839.   (interactive "P")
  4840.   (if (not (zerop (prefix-numeric-value arg)))
  4841.       (dired-do-create-files 'move (function dired-rename-file)
  4842.                    "Move" arg dired-keep-marker-rename
  4843.                    (function
  4844.                 (lambda (list)
  4845.                   (if (= (length list) 1)
  4846.                       "Rename %s to: "
  4847.                     "Move %s to: "))))
  4848.     (setq dired-dwim-target (not dired-dwim-target))
  4849.     (message "dired-dwim-target is %s." (if dired-dwim-target "ON" "OFF"))))
  4850.  
  4851. (defun dired-rename-file (from to ok-flag)
  4852.   (dired-handle-overwrite to)
  4853.   (let ((insert (assoc (file-name-as-directory from) dired-subdir-alist)))
  4854.     (rename-file from to ok-flag) ; error is caught in -create-files
  4855.     ;; Silently rename the visited file of any buffer visiting this file.
  4856.     (dired-rename-update-buffers from to insert)))
  4857.  
  4858. (defun dired-rename-update-buffers (from to &optional insert)
  4859.   (if (get-file-buffer from)
  4860.       (save-excursion
  4861.     (set-buffer (get-file-buffer from))
  4862.     (let ((modflag (buffer-modified-p)))
  4863.       (set-visited-file-name to)    ; kills write-file-hooks
  4864.       (set-buffer-modified-p modflag)))
  4865.     ;; It's a directory.  More work to do.
  4866.     (let ((blist (buffer-list))
  4867.       (from-dir (file-name-as-directory from))
  4868.       (to-dir (file-name-as-directory to)))
  4869.       (save-excursion
  4870.     (while blist
  4871.       (set-buffer (car blist))
  4872.       (setq blist (cdr blist))
  4873.       (cond
  4874.        (buffer-file-name
  4875.         (if (dired-in-this-tree buffer-file-name from-dir)
  4876.         (let ((modflag (buffer-modified-p)))
  4877.           (unwind-protect
  4878.               (set-visited-file-name
  4879.                (concat to-dir (substring buffer-file-name
  4880.                          (length from-dir))))
  4881.             (set-buffer-modified-p modflag)))))
  4882.        (dired-directory
  4883.         (if (string-equal from-dir (expand-file-name default-directory))
  4884.         ;; If top level directory was renamed, lots of things
  4885.         ;; have to be updated.
  4886.         (progn
  4887.           (dired-unadvertise from-dir)
  4888.           (setq default-directory to-dir
  4889.             dired-directory
  4890.             ;; Need to beware of wildcards.
  4891.             (expand-file-name 
  4892.              (file-name-nondirectory dired-directory)
  4893.              to-dir))
  4894.           (let ((new-name (file-name-nondirectory
  4895.                    (directory-file-name dired-directory))))
  4896.             ;; Try to rename buffer, but just leave old name if new
  4897.             ;; name would already exist (don't try appending "<%d>")
  4898.             ;; Why?  --sandy 19-8-94
  4899.             (or (get-buffer new-name)
  4900.             (rename-buffer new-name)))
  4901.           (dired-advertise))
  4902.           (and insert
  4903.            (assoc (file-name-directory (directory-file-name to))
  4904.               dired-subdir-alist)
  4905.            (dired-insert-subdir to))))))))))
  4906.  
  4907. ;;; Making symbolic links
  4908.  
  4909. (defun dired-do-symlink (&optional arg)
  4910.   "Make symbolic links to current file or all marked (or next ARG) files.
  4911. When operating on just the current file, you specify the new name.
  4912. When operating on multiple or marked files, you specify a directory
  4913. and new symbolic links are made in that directory
  4914. with the same names that the files currently have."
  4915.   (interactive "P")
  4916.   (dired-do-create-files 'symlink (function make-symbolic-link)
  4917.                "SymLink" arg dired-keep-marker-symlink))
  4918.  
  4919. ;; Relative symlinks:
  4920. ;; make-symbolic no longer expands targets (as of at least 18.57),
  4921. ;; so the code to call ln has been removed.
  4922.  
  4923. (defun dired-do-relsymlink (&optional arg)
  4924.   "Symlink all marked (or next ARG) files into a directory,
  4925. or make a symbolic link to the current file.
  4926. This creates relative symbolic links like
  4927.  
  4928.     foo -> ../bar/foo
  4929.  
  4930. not absolute ones like
  4931.  
  4932.     foo -> /ugly/path/that/may/change/any/day/bar/foo"
  4933.   (interactive "P")
  4934.   (dired-do-create-files 'relsymlink (function dired-make-relative-symlink)
  4935.              "RelSymLink" arg dired-keep-marker-symlink))
  4936.  
  4937. (defun dired-make-relative-symlink (target linkname
  4938.                        &optional ok-if-already-exists)
  4939.   "Make a relative symbolic link pointing to TARGET with name LINKNAME.
  4940. Three arguments: FILE1 FILE2 &optional OK-IF-ALREADY-EXISTS
  4941. The link is relative (if possible), for example
  4942.  
  4943.     \"/vol/tex/bin/foo\" \"/vol/local/bin/foo\"
  4944.  
  4945. results in
  4946.  
  4947.     \"../../tex/bin/foo\" \"/vol/local/bin/foo\""
  4948.   (interactive
  4949.    (let ((target (read-string "Make relative symbolic link to file: ")))
  4950.      (list
  4951.       target
  4952.       (read-file-name (format "Make relsymlink to file %s: " target))
  4953.       0)))
  4954.   (let* ((target (expand-file-name target))
  4955.      (linkname (expand-file-name linkname))
  4956.      (handler (or (find-file-name-handler
  4957.                linkname 'dired-make-relative-symlink)
  4958.               (find-file-name-handler
  4959.                target 'dired-make-relative-symlink))))
  4960.     (if handler
  4961.     (funcall handler 'dired-make-relative-symlink target linkname
  4962.          ok-if-already-exists)
  4963.       (setq target (directory-file-name target)
  4964.         linkname (directory-file-name linkname))
  4965.       (make-symbolic-link
  4966.        (dired-make-relative target (file-name-directory linkname) t)
  4967.        linkname ok-if-already-exists))))
  4968.  
  4969. ;;; Hard links -- adding names to files
  4970.  
  4971. (defun dired-do-hardlink (&optional arg)
  4972.   "Add names (hard links) current file or all marked (or next ARG) files.
  4973. When operating on just the current file, you specify the new name.
  4974. When operating on multiple or marked files, you specify a directory
  4975. and new hard links are made in that directory
  4976. with the same names that the files currently have."
  4977.   (interactive "P")
  4978.   (dired-do-create-files 'hardlink (function add-name-to-file)
  4979.                "HardLink" arg dired-keep-marker-hardlink))
  4980.  
  4981.  
  4982. ;;;; ---------------------------------------------------------------
  4983. ;;;; Running process on marked files
  4984. ;;;; ---------------------------------------------------------------
  4985. ;;;
  4986. ;;;  Commands for shell processes are in dired-shell.el.
  4987.  
  4988. ;;; Internal functions for running subprocesses,
  4989. ;;; checking and logging of their errors.
  4990.  
  4991. (defun dired-call-process (program discard &rest arguments)
  4992.   ;; Run PROGRAM with output to current buffer unless DISCARD is t.
  4993.   ;; Remaining arguments are strings passed as command arguments to PROGRAM.
  4994.   ;; Returns program's exit status, as an integer.
  4995.   ;; This is a separate function so that efs can redefine it.
  4996.   (let ((return
  4997.      (apply 'call-process program nil (not discard) nil arguments)))
  4998.     (if (and (not (equal shell-file-name program))
  4999.          (integerp return))
  5000.     return
  5001.       ;; Fudge return code by looking for errors in current buffer.
  5002.       (if (zerop (buffer-size)) 0 1))))
  5003.       
  5004. (defun dired-check-process (msg program &rest arguments)
  5005.   ;; Display MSG while running PROGRAM, and check for output.
  5006.   ;; Remaining arguments are strings passed as command arguments to PROGRAM.
  5007.   ;; On error, insert output in a log buffer and return the
  5008.   ;; offending ARGUMENTS or PROGRAM.
  5009.   ;; Caller can cons up a list of failed args.
  5010.   ;; Else returns nil for success.
  5011.   (let ((err-buffer (get-buffer-create " *dired-check-process output*"))
  5012.     (dir default-directory))
  5013.     (message "%s..." msg)
  5014.     (save-excursion
  5015.       ;; Get a clean buffer for error output:
  5016.       (set-buffer err-buffer)
  5017.       (erase-buffer)
  5018.       (setq default-directory dir)    ; caller's default-directory
  5019.       (if (not
  5020.        (eq 0 (apply (function dired-call-process) program nil arguments)))
  5021.       (progn
  5022.         (dired-log (buffer-name (current-buffer))
  5023.                (concat program " " (prin1-to-string arguments) "\n"))
  5024.         (dired-log (buffer-name (current-buffer)) err-buffer)
  5025.         (or arguments program t))
  5026.     (kill-buffer err-buffer)
  5027.     (message "%s...done" msg)
  5028.     nil))))
  5029.  
  5030. ;;; Changing file attributes
  5031.  
  5032. (defun dired-do-chxxx (attribute-name program op-symbol arg)
  5033.   ;; Change file attributes (mode, group, owner) of marked files and
  5034.   ;; refresh their file lines.
  5035.   ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  5036.   ;; PROGRAM is the program used to change the attribute.
  5037.   ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
  5038.   ;; ARG describes which files to use, like in dired-get-marked-files.
  5039.   (let* ((files (dired-get-marked-files t arg))
  5040.      (new-attribute
  5041.       (dired-mark-read-string
  5042.        (concat "Change " attribute-name " of %s to: ")
  5043.        nil op-symbol arg files))
  5044.      (operation (concat program " " new-attribute))
  5045.      (failures
  5046.       (dired-bunch-files 10000 (function dired-check-process)
  5047.                  (list operation program new-attribute)
  5048.                  files)))
  5049.     (dired-do-redisplay arg);; moves point if ARG is an integer
  5050.     (if failures
  5051.     (dired-log-summary (buffer-name (current-buffer))
  5052.                (format "%s: error" operation) nil))))
  5053.  
  5054. (defun dired-do-chmod (&optional arg)
  5055.   "Change the mode of the marked (or next ARG) files.
  5056. This calls chmod, thus symbolic modes like `g+w' are allowed."
  5057.   (interactive "P")
  5058.   (dired-do-chxxx "Mode" "chmod" 'chmod arg))
  5059.  
  5060. (defun dired-do-chgrp (&optional arg)
  5061.   "Change the group of the marked (or next ARG) files."
  5062.   (interactive "P")
  5063.   (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
  5064.  
  5065. (defun dired-do-chown (&optional arg)
  5066.   "Change the owner of the marked (or next ARG) files."
  5067.   (interactive "P")
  5068.   (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
  5069.  
  5070. ;;; Utilities for running processes on marked files.
  5071.  
  5072. ;; Process all the files in FILES in batches of a convenient size,
  5073. ;; by means of (FUNCALL FUNCTION ARGS... SOME-FILES...).
  5074. ;; Batches are chosen to need less than MAX chars for the file names,
  5075. ;; allowing 3 extra characters of separator per file name.
  5076. (defun dired-bunch-files (max function args files)
  5077.   (let (pending
  5078.     (pending-length 0)
  5079.     failures)
  5080.     ;; Accumulate files as long as they fit in MAX chars,
  5081.     ;; then process the ones accumulated so far.
  5082.     (while files
  5083.       (let* ((thisfile (car files))
  5084.          (thislength (+ (length thisfile) 3))
  5085.          (rest (cdr files)))
  5086.     ;; If we have at least 1 pending file
  5087.     ;; and this file won't fit in the length limit, process now.
  5088.     (if (and pending (> (+ thislength pending-length) max))
  5089.         (setq failures
  5090.           (nconc (apply function (append args pending))
  5091.              failures)
  5092.           pending nil
  5093.           pending-length 0))
  5094.     ;; Do (setq pending (cons thisfile pending))
  5095.     ;; but reuse the cons that was in `files'.
  5096.     (setcdr files pending)
  5097.     (setq pending files)
  5098.     (setq pending-length (+ thislength pending-length))
  5099.     (setq files rest)))
  5100.     (nconc (apply function (append args pending))
  5101.        failures)))
  5102.  
  5103.  
  5104. ;;;; ---------------------------------------------------------------
  5105. ;;;; Calculating data or properties for marked files.
  5106. ;;;; ---------------------------------------------------------------
  5107.  
  5108. (defun dired-do-total-size (&optional arg)
  5109.   "Show total size of all marked (or next ARG) files."
  5110.   (interactive "P")
  5111.   (let* ((result (dired-map-over-marks (dired-get-file-size) arg))
  5112.      (total (apply (function +) result))
  5113.      (num (length result)))
  5114.     (message "%d bytes (%d kB) in %s file%s"
  5115.          total (/ total 1024) num (dired-plural-s num))
  5116.     total))
  5117.  
  5118. (defun dired-get-file-size ()
  5119.   ;; Returns the file size in bytes of the current file, as an integer.
  5120.   ;; Assumes that it is on a valid file line. It's the caller's responsibility
  5121.   ;; to ensure this. Assumes that match 0 for dired-re-month-and-time is
  5122.   ;; at the end of the file size.
  5123.   (end-of-line)
  5124.   (search-backward-regexp dired-re-month-and-time)
  5125.   (skip-chars-backward " ")
  5126.   (string-to-int (buffer-substring (point)
  5127.                    (progn (skip-chars-backward "0-9")
  5128.                       (point)))))
  5129.  
  5130. (defun dired-copy-filenames-as-kill (&optional arg)
  5131.   "Copy names of marked (or next ARG) files into the kill ring.
  5132. The names are separated by a space, and may be copied into other buffers
  5133. with \\[yank].  The list of names is also stored in the variable 
  5134. `dired-marked-files' for possible manipulation in the *scratch* buffer.
  5135.  
  5136. With a 0 prefix argument, use the pathname relative to the top-level dired
  5137. directory for each marked file.
  5138.  
  5139. With a prefix \\[universal-argument], use the complete pathname of each 
  5140. marked file.
  5141.  
  5142. With a prefix \\[universal-argument] \\[universal-argument], copy the complete
  5143. file line.  In this case, the lines are separated by newlines.
  5144.  
  5145. If on a subdirectory headerline and no prefix argument given, use the
  5146. subdirectory name instead."
  5147.   (interactive "P")
  5148.   (let (res)
  5149.     (cond
  5150.      ((and (null arg) (setq res (dired-get-subdir)))
  5151.       (kill-new res)
  5152.       (message "Copied %s into kill ring." res))
  5153.      ((equal arg '(16))
  5154.       (setq dired-marked-files
  5155.         (dired-map-over-marks
  5156.          (concat " " ; Don't copy the mark.
  5157.              (buffer-substring
  5158.               (progn (beginning-of-line) (1+ (point)))
  5159.               (progn (skip-chars-forward "^\n\r") (point))))
  5160.              nil))
  5161.       (let ((len (length dired-marked-files)))
  5162.     (kill-new (concat
  5163.            (mapconcat 'identity dired-marked-files "\n")
  5164.            "\n"))
  5165.     (message "Copied %d file line%s into kill ring."
  5166.          len (dired-plural-s len))))
  5167.      (t
  5168.       (setq dired-marked-files
  5169.         (cond
  5170.          ((null arg)
  5171.           (dired-get-marked-files 'no-dir))
  5172.          ((eq arg 0)
  5173.           (dired-get-marked-files t))
  5174.          ((integerp arg)
  5175.           (dired-get-marked-files 'no-dir arg))
  5176.          ((equal arg '(4))
  5177.           (dired-get-marked-files))
  5178.          (t (error "Invalid prefix %s" arg))))
  5179.       (let ((len (length dired-marked-files)))
  5180.     (kill-new (mapconcat 'identity dired-marked-files " "))
  5181.     (message "Copied %d file name%s into kill ring."
  5182.          len (dired-plural-s len)))))))
  5183.  
  5184.  
  5185. ;;;; -----------------------------------------------------------
  5186. ;;;; Killing subdirectories
  5187. ;;;; -----------------------------------------------------------
  5188. ;;;
  5189. ;;;  These commands actually remove text from the dired buffer.
  5190.  
  5191. (defun dired-kill-subdir (&optional remember-marks tree)
  5192.   "Remove all lines of current subdirectory.
  5193. Lower levels are unaffected.  If given a prefix when called interactively,
  5194. kills the entire directory tree below the current subdirectory."
  5195.   ;; With optional REMEMBER-MARKS, return a mark-alist.
  5196.   (interactive (list nil current-prefix-arg))
  5197.   (let ((cur-dir (dired-current-directory)))
  5198.     (if (string-equal cur-dir (expand-file-name default-directory))
  5199.     (error "Attempt to kill top level directory"))
  5200.     (if tree
  5201.     (dired-kill-tree cur-dir remember-marks)
  5202.       (let ((beg (dired-subdir-min))
  5203.         (end (dired-subdir-max))
  5204.         buffer-read-only)
  5205.     (prog1
  5206.         (if remember-marks (dired-remember-marks beg end))
  5207.       (goto-char beg)
  5208.       (or (bobp) (forward-char -1)) ; gobble separator
  5209.       (delete-region (point) end)
  5210.       (dired-unsubdir cur-dir)
  5211.       (dired-update-mode-line)
  5212.       (dired-update-mode-line-modified t))))))
  5213.  
  5214. (defun dired-kill-tree (dirname &optional remember-marks)
  5215.   "Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
  5216. With optional arg REMEMBER-MARKS, return an alist of marked files."
  5217.   (interactive "DKill tree below directory: ")
  5218.   (let ((s-alist dired-subdir-alist) dir m-alist)
  5219.     (while s-alist
  5220.       (setq dir (car (car s-alist))
  5221.         s-alist (cdr s-alist))
  5222.       (if (and (not (string-equal dir dirname))
  5223.            (dired-in-this-tree dir dirname)
  5224.            (dired-goto-subdir dir))
  5225.       (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
  5226.     (dired-update-mode-line)
  5227.     (dired-update-mode-line-modified t)
  5228.     m-alist))
  5229.  
  5230.  
  5231. ;;;; ------------------------------------------------------------
  5232. ;;;; Killing file lines
  5233. ;;;; ------------------------------------------------------------
  5234. ;;;
  5235. ;;;  Uses selective diplay, rather than removing lines from the buffer.
  5236.  
  5237. (defun dired-do-kill-file-lines (&optional arg)
  5238.   "Kill all marked file lines, or those indicated by the prefix argument.
  5239. Killing file lines means hiding them with selective display.  Giving
  5240. a zero prefix redisplays all killed file lines."
  5241.   (interactive "P")
  5242.   (or selective-display
  5243.       (error "selective-display must be t for file line killing to work!"))
  5244.   (if (eq arg 0)
  5245.       (dired-do-unhide dired-kill-marker-char
  5246.                "Successfully resuscitated %d file line%s."
  5247.                dired-keep-marker-kill)
  5248.     (let ((files
  5249.        (length
  5250.         (dired-map-over-marks
  5251.          (progn
  5252.            (beginning-of-line)
  5253.            (subst-char-in-region (1- (point)) (point) ?\n ?\r)
  5254.            (dired-substitute-marker (point) (following-char)
  5255.                     dired-kill-marker-char)
  5256.            (dired-update-marker-counters dired-marker-char t)
  5257.            t)
  5258.          arg))))
  5259.       ;; Beware of extreme apparent save-excursion lossage here.
  5260.       (let ((opoint (point)))
  5261.     (skip-chars-backward "^\n\r")
  5262.     (if (= (preceding-char) ?\n)
  5263.         (goto-char opoint)
  5264.       (setq opoint (- opoint (point)))
  5265.       (beginning-of-line)
  5266.       (skip-chars-forward "^\n\r" (+ (point) opoint))))
  5267.       (dired-update-mode-line-modified)
  5268.       (message "Killed %d file line%s." files (dired-plural-s files)))))
  5269.  
  5270.  
  5271. ;;;; ----------------------------------------------------------------
  5272. ;;;; Omitting files.
  5273. ;;;; ----------------------------------------------------------------
  5274.  
  5275. ;; Marked files are never omitted.
  5276. ;; Adapted from code submitted by:
  5277. ;; Michael D. Ernst, mernst@theory.lcs.mit.edu, 1/11/91
  5278. ;; Changed to work with selective display by Sandy Rutherford, 13/12/92.
  5279. ;; For historical reasons, we still use the term expunge, although nothing
  5280. ;; is expunged from the buffer.
  5281.  
  5282. (defun dired-omit-toggle (&optional arg)
  5283.   "Toggle between displaying and omitting files matching
  5284. `dired-omit-regexps' in the current subdirectory.
  5285. With a positive prefix, omits files in the entire tree dired buffer.
  5286. With a negative prefix, forces all files in the tree dired buffer to be
  5287. displayed."
  5288.   (interactive "P")
  5289.   (if arg
  5290.       (let ((arg (prefix-numeric-value arg)))
  5291.     (if (>= arg 0)
  5292.         (dired-omit-expunge nil t)
  5293.       (dired-do-unhide dired-omit-marker-char "")
  5294.       (mapcar
  5295.        (function
  5296.         (lambda (elt)
  5297.           (setcar (nthcdr 2 elt) nil)))
  5298.        dired-subdir-alist)))
  5299.     (if (dired-current-subdir-omitted-p)
  5300.     (save-restriction
  5301.       (narrow-to-region (dired-subdir-min) (dired-subdir-max))
  5302.       (dired-do-unhide dired-omit-marker-char "")
  5303.       (setcar (nthcdr 2 (assoc
  5304.                  (dired-current-directory) dired-subdir-alist))
  5305.           nil)
  5306.       (setq dired-subdir-omit nil))
  5307.       (dired-omit-expunge)
  5308.       (setq dired-subdir-omit t)))
  5309.   (dired-update-mode-line t))
  5310.  
  5311. (defun dired-current-subdir-omitted-p ()
  5312.   ;; Returns t if the current subdirectory is omited.
  5313.   (nth 2 (assoc (dired-current-directory) dired-subdir-alist)))
  5314.  
  5315. (defun dired-remember-omitted ()
  5316.   ;; Returns a list of omitted subdirs.
  5317.   (let ((alist dired-subdir-alist)
  5318.     result elt)
  5319.     (while alist
  5320.       (setq elt (car alist)
  5321.         alist (cdr alist))
  5322.       (if (nth 2 elt)
  5323.       (setq result (cons (car elt) result))))
  5324.     result))
  5325.  
  5326. (defun dired-omit-expunge (&optional regexp full-buffer)
  5327.   ;; Hides all unmarked files matching REGEXP.
  5328.   ;; If REGEXP is nil or not specified, uses `dired-omit-regexps',
  5329.   ;; and also omits filenames ending in `dired-omit-extensions'.
  5330.   ;; If REGEXP is the empty string, this function is a no-op.
  5331.   (let ((omit-re (or regexp (dired-omit-regexp)))
  5332.     (alist dired-subdir-alist)
  5333.     elt min)
  5334.     (if (null omit-re)
  5335.     0
  5336.       (if full-buffer
  5337.       (prog1
  5338.           (dired-omit-region (point-min) (point-max) omit-re)
  5339.         ;; Set omit property in dired-subdir-alist
  5340.         (while alist
  5341.           (setq elt (car alist)
  5342.             min (dired-get-subdir-min elt)
  5343.             alist (cdr alist))
  5344.           (if (and (<= (point-min) min) (>= (point-max) min))
  5345.           (setcar (nthcdr 2 elt) t))))
  5346.     (prog1
  5347.         (dired-omit-region (dired-subdir-min) (dired-subdir-max) omit-re)
  5348.       (setcar
  5349.        (nthcdr 2 (assoc (dired-current-directory)
  5350.                 dired-subdir-alist))
  5351.        t))))))
  5352.  
  5353. (defun dired-omit-region (start end regexp)
  5354.   ;; Omits files matching regexp in region. Returns count.
  5355.   (save-restriction
  5356.     (narrow-to-region start end)
  5357.     (let ((hidden-subdirs (dired-remember-hidden))
  5358.       buffer-read-only count)
  5359.       (or selective-display
  5360.       (error "selective-display must be t for file omission to work!"))
  5361.       (dired-omit-unhide-region start end)
  5362.       (let ((dired-marker-char dired-omit-marker-char)
  5363.         ;; since all subdirs are now unhidden, this fakes
  5364.         ;; dired-move-to-end-of-filename into working faster
  5365.         (selective-display nil))
  5366.     (or dired-omit-silent
  5367.         dired-in-query (message "Omitting..."))
  5368.     (if (dired-mark-unmarked-files regexp nil nil 'no-dir)
  5369.         (setq count (dired-do-hide
  5370.              dired-marker-char
  5371.              (and (memq dired-omit-silent '(nil 0))
  5372.                   (not dired-in-query)
  5373.                   "Omitted %d line%s.")))
  5374.       (or dired-omit-silent dired-in-query
  5375.           (message "(Nothing to omit)"))))
  5376.       (save-excursion        ;hide subdirs that were hidden
  5377.     (mapcar (function (lambda (dir)
  5378.                 (if (dired-goto-subdir dir)
  5379.                 (dired-hide-subdir 1))))
  5380.         hidden-subdirs))
  5381.       count)))
  5382.  
  5383. (defun dired-omit-unhide-region (beg end)
  5384.   ;; Unhides hidden, but not marked files in the region.
  5385.   (save-excursion
  5386.     (save-restriction
  5387.       (narrow-to-region beg end)
  5388.       (goto-char (point-min))
  5389.       (while (search-forward "\r" nil t)
  5390.     (and (char-equal (following-char) ?\ )
  5391.          (subst-char-in-region (1- (point)) (point) ?\r ?\n))))))
  5392.  
  5393. (defun dired-do-unhide (char &optional fmt marker)
  5394.   ;; Unhides files marked with CHAR. Optional FMT is a message
  5395.   ;; to be displayed. Note that after unhiding, we will need to re-hide
  5396.   ;; files belonging to hidden subdirs.
  5397.   (save-excursion
  5398.     (goto-char (point-min))
  5399.     (let ((count 0)
  5400.       (string (concat "\r" (char-to-string char)))
  5401.       (hidden-subdirs (dired-remember-hidden))
  5402.       (new (if marker (concat "\n" (char-to-string marker)) "\n "))
  5403.       buffer-read-only)
  5404.       (while (search-forward string nil t)
  5405.     (replace-match new)
  5406.     (setq count (1+ count)))
  5407.       (or (equal "" fmt)
  5408.       (message (or fmt "Unhid %d line%s.") count (dired-plural-s count)))
  5409.       (goto-char (point-min))
  5410.       (mapcar (function (lambda (dir)
  5411.               (if (dired-goto-subdir dir)
  5412.                   (dired-hide-subdir 1 t))))
  5413.           hidden-subdirs)
  5414.       (if marker (dired-update-mode-line-modified t))
  5415.       count)))
  5416.  
  5417. (defun dired-do-hide (char &optional fmt)
  5418.   ;; Hides files marked with CHAR. Otional FMT is a message
  5419.   ;; to be displayed. FMT is a format string taking args the number
  5420.   ;; of hidden file lines, and dired-plural-s.
  5421.   (save-excursion
  5422.     (goto-char (point-min))
  5423.     (let ((count 0)
  5424.       (string (concat "\n" (char-to-string char)))
  5425.       buffer-read-only)
  5426.       (while (search-forward string nil t)
  5427.     (subst-char-in-region (match-beginning 0)
  5428.                   (1+ (match-beginning 0)) ?\n ?\r t)
  5429.     (setq count (1+ count)))
  5430.       (if fmt
  5431.       (message fmt count (dired-plural-s count)))
  5432.       count)))
  5433.  
  5434. (defun dired-omit-regexp ()
  5435.   (let (rgxp)
  5436.     (if dired-omit-extensions
  5437.     (setq rgxp (concat
  5438.             ".\\("
  5439.             (mapconcat 'regexp-quote dired-omit-extensions "\\|")
  5440.             "\\)\\'")))
  5441.     (if dired-omit-regexps
  5442.     (setq rgxp
  5443.           (concat
  5444.            rgxp
  5445.            (and rgxp "\\|")
  5446.            (mapconcat 'identity dired-omit-regexps "\\|"))))
  5447.     rgxp))
  5448.  
  5449. (defun dired-mark-unmarked-files (regexp msg &optional unflag-p localp)
  5450.   ;; Marks unmarked files matching REGEXP, displaying MSG.
  5451.   ;; REGEXP is matched against the complete pathname, unless localp is
  5452.   ;; specified.
  5453.   ;; Does not re-mark files which already have a mark.
  5454.   ;; Returns t if any work was done, nil otherwise.
  5455.   (let ((dired-marker-char (if unflag-p ?\  dired-marker-char))
  5456.     fn)
  5457.     (dired-mark-if
  5458.      (and
  5459.       ;; not already marked
  5460.       (eq (following-char) ?\ )
  5461.       ;; uninteresting
  5462.       (setq fn (dired-get-filename localp t))
  5463.       (string-match regexp fn))
  5464.      msg)))
  5465.  
  5466. (defun dired-add-omit-regexp (rgxp &optional how)
  5467.   "Adds a new regular expression to the list of omit regular expresions.
  5468. With a non-zero numeric prefix argument, deletes a regular expresion from 
  5469. the list.
  5470.  
  5471. With a prefix argument \\[universal-argument], adds a new extension to
  5472. the list of file name extensions omitted.
  5473. With a prefix argument \\[universal-argument] \\[universal-argument], deletes
  5474. a file name extension from the list.
  5475.  
  5476. With a prefix 0, reports on the current omit regular expressions and 
  5477. extensions."
  5478.   (interactive
  5479.    (list
  5480.     (cond
  5481.      ((null current-prefix-arg)
  5482.       (read-string "New omit regular expression: "))
  5483.      ((equal '(4) current-prefix-arg)
  5484.       (read-string "New omit extension (\".\" is not implicit): "))
  5485.      ((equal '(16) current-prefix-arg)
  5486.       (completing-read
  5487.        "Remove from omit extensions (type SPACE for options): "
  5488.        (mapcar 'list dired-omit-extensions) nil t))
  5489.      ((eq 0 current-prefix-arg)
  5490.       nil)
  5491.      (t
  5492.       (completing-read
  5493.        "Remove from omit regexps (type SPACE for options): "
  5494.        (mapcar 'list dired-omit-regexps) nil t)))
  5495.     current-prefix-arg))
  5496.   (let (remove)
  5497.     (cond
  5498.      ((null how)
  5499.       (if (member rgxp dired-omit-regexps)
  5500.       (progn
  5501.         (describe-variable 'dired-omit-regexps)
  5502.         (error "%s is already included in the list." rgxp))
  5503.     (setq dired-omit-regexps (cons rgxp dired-omit-regexps))))
  5504.      ((equal how '(4))
  5505.       (if (member rgxp dired-omit-extensions)
  5506.       (progn
  5507.         (describe-variable 'dired-omit-extensions)
  5508.         (error "%s is already included in list." rgxp))
  5509.     (setq dired-omit-extensions (cons rgxp dired-omit-extensions))))
  5510.      ((equal how '(16))
  5511.       (let ((tail (member rgxp dired-omit-extensions)))
  5512.     (if tail
  5513.         (setq dired-omit-extensions
  5514.           (delq (car tail) dired-omit-extensions)
  5515.           remove t)
  5516.       (setq remove 'ignore))))
  5517.      ((eq 0 how)
  5518.       (setq remove 'ignore)
  5519.       (if (featurep 'ehelp)
  5520.       (with-electric-help
  5521.        (function
  5522.         (lambda ()
  5523.           (princ "Omit extensions (dired-omit-extensions <V>):\n")
  5524.           (dired-format-columns-of-files dired-omit-extensions)
  5525.           (princ "\n")
  5526.           (princ "Omit regular expressions (dired-omit-regexps <V>):\n")
  5527.           (dired-format-columns-of-files dired-omit-regexps)
  5528.           nil)))
  5529.     (with-output-to-temp-buffer "*Help*"
  5530.       (princ "Omit extensions (dired-omit-extensions <V>):\n")
  5531.       (dired-format-columns-of-files dired-omit-extensions)
  5532.       (princ "\n")
  5533.       (princ "Omit regular expressions (dired-omit-regexps <V>):\n")
  5534.       (dired-format-columns-of-files dired-omit-regexps)
  5535.       (print-help-return-message))))
  5536.      (t
  5537.       (let ((tail (member rgxp dired-omit-regexps)))
  5538.     (if tail
  5539.         (setq dired-omit-regexps (delq (car tail) dired-omit-regexps)
  5540.           remove t)
  5541.       (setq remove 'ignore)))))
  5542.     (or (eq remove 'ignore)
  5543.     (save-excursion
  5544.       (mapcar
  5545.        (function
  5546.         (lambda (dir)
  5547.           (if (dired-goto-subdir dir)
  5548.           (progn
  5549.             (if remove
  5550.             (save-restriction
  5551.               (narrow-to-region
  5552.                (dired-subdir-min) (dired-subdir-max))
  5553.               (dired-do-unhide dired-omit-marker-char "")))
  5554.             (dired-omit-expunge)))))
  5555.        (dired-remember-omitted))))))
  5556.  
  5557.  
  5558.  
  5559. ;;;; ----------------------------------------------------------------
  5560. ;;;; Directory hiding.
  5561. ;;;; ----------------------------------------------------------------
  5562. ;;;
  5563. ;;; To indicate a hidden subdir, we actually insert "..." in the buffer.
  5564. ;;; Aside from giving the look of ellipses (even though
  5565. ;;; selective-display-ellipses is nil), it allows us to tell the difference
  5566. ;;; between a dir with a single omitted file, and a hidden subdir with one
  5567. ;;; file.
  5568.  
  5569. (defun dired-subdir-hidden-p (dir)
  5570.   (save-excursion
  5571.     (and selective-display
  5572.      (dired-goto-subdir dir)
  5573.      (looking-at "\\.\\.\\.\r"))))
  5574.  
  5575. (defun dired-unhide-subdir ()
  5576.   (let (buffer-read-only)
  5577.     (goto-char (dired-subdir-min))
  5578.     (skip-chars-forward "^\n\r")
  5579.     (skip-chars-backward "." (- (point) 3))
  5580.     (if (looking-at "\\.\\.\\.\r") (delete-char 4))
  5581.     (dired-omit-unhide-region (point) (dired-subdir-max))))
  5582.  
  5583. (defun dired-hide-check ()
  5584.   (or selective-display
  5585.       (error "selective-display must be t for subdir hiding to work!")))
  5586.  
  5587. (defun dired-hide-subdir (arg &optional really)
  5588.   "Hide or unhide the current subdirectory and move to next directory.
  5589. Optional prefix arg is a repeat factor.
  5590. Use \\[dired-hide-all] to (un)hide all directories.
  5591. With the optional argument REALLY, we always hide 
  5592. the subdir, regardless of dired-subdir-hidden-p."
  5593.   ;; The arg REALLY is needed because when we unhide
  5594.   ;; omitted files in a hidden subdir, we want to
  5595.   ;; re-hide the subdir, regardless of whether dired
  5596.   ;; thinks it's already hidden.
  5597.   (interactive "p")
  5598.   (dired-hide-check)
  5599.   (dired-save-excursion
  5600.     (while (>=  (setq arg (1- arg)) 0)
  5601.       (let* ((cur-dir (dired-current-directory))
  5602.          (hidden-p (and (null really)
  5603.                 (dired-subdir-hidden-p cur-dir)))
  5604.        (elt (assoc cur-dir dired-subdir-alist))
  5605.        (end-pos (1- (dired-get-subdir-max elt)))
  5606.        buffer-read-only)
  5607.     ;; keep header line visible, hide rest
  5608.     (goto-char (dired-get-subdir-min elt))
  5609.     (skip-chars-forward "^\n\r")
  5610.     (skip-chars-backward "." (- (point) 3))
  5611.       (if hidden-p
  5612.       (progn
  5613.         (if (looking-at "\\.\\.\\.\r")
  5614.         (progn
  5615.           (delete-char 3)
  5616.           (setq end-pos (- end-pos 3))))
  5617.         (dired-omit-unhide-region (point) end-pos))
  5618.     (if (looking-at "\\.\\.\\.\r")
  5619.         (goto-char (match-end 0))
  5620.       (insert "...")
  5621.       (setq end-pos (+ end-pos 3)))
  5622.     (subst-char-in-region (point) end-pos ?\n ?\r)))
  5623.       (dired-next-subdir 1 t))))
  5624.   
  5625. (defun dired-hide-all (arg)
  5626.   "Hide all subdirectories, leaving only their header lines.
  5627. If there is already something hidden, make everything visible again.
  5628. Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
  5629.   (interactive "P")
  5630.   (dired-hide-check)
  5631.   (let (buffer-read-only)
  5632.     (dired-save-excursion
  5633.       (if (let ((alist dired-subdir-alist)
  5634.         (hidden nil))
  5635.         (while (and alist (null hidden))
  5636.           (setq hidden (dired-subdir-hidden-p (car (car alist)))
  5637.             alist (cdr alist)))
  5638.         hidden)
  5639.       ;; unhide
  5640.       (let ((alist dired-subdir-alist))
  5641.         (while alist
  5642.           (goto-char (dired-get-subdir-min (car alist)))
  5643.           (skip-chars-forward "^\n\r")
  5644.           (delete-region (point) (progn (skip-chars-backward ".") (point)))
  5645.           (setq alist (cdr alist)))
  5646.         (dired-omit-unhide-region (point-min) (point-max)))
  5647.     ;; hide
  5648.     (let ((alist dired-subdir-alist))
  5649.       (while alist
  5650.         (dired-goto-subdir (car (car alist)))
  5651.         (dired-hide-subdir 1 t)
  5652.         (setq alist (cdr alist))))))))
  5653.  
  5654.  
  5655. ;;;; -----------------------------------------------------------------
  5656. ;;;; Automatic dired buffer maintenance.
  5657. ;;;; -----------------------------------------------------------------
  5658. ;;;
  5659. ;;;  Keeping Dired buffers in sync with the filesystem and with each
  5660. ;;;  other.
  5661. ;;;  When used with efs on remote directories, buffer maintainence is
  5662. ;;;  done asynch.
  5663.  
  5664. (defun dired-buffers-for-dir (dir-or-list &optional check-wildcard)
  5665. ;; Return a list of buffers that dired DIR-OR-LIST
  5666. ;; (top level or in-situ subdir).
  5667. ;; The list is in reverse order of buffer creation, most recent last.
  5668. ;; As a side effect, killed dired buffers for DIR are removed from
  5669. ;; dired-buffers. If DIR-OR-LIST is a wildcard or list, returns any
  5670. ;; dired buffers for which DIR-OR-LIST is equal to `dired-directory'.
  5671. ;; If check-wildcard is non-nil, only returns buffers which contain dir-or-list
  5672. ;; exactly, including the wildcard part.
  5673.   (let ((alist dired-buffers)
  5674.     (as-dir (and (stringp dir-or-list)
  5675.              (file-name-as-directory dir-or-list)))
  5676.     result buff elt)
  5677.     (while alist
  5678.       (setq buff (cdr (setq elt (car alist)))
  5679.         alist (cdr alist))
  5680.       ;; dired-in-this-tree is not fast. It doesn't pay to use this to check
  5681.       ;; whether the buffer is a good candidate.
  5682.       (if (buffer-name buff)
  5683.       (save-excursion
  5684.         (set-buffer buff)
  5685.         (if (or (equal dir-or-list dired-directory) ; the wildcard case.
  5686.             (and as-dir
  5687.              (not (and check-wildcard
  5688.                    (string-equal
  5689.                     as-dir
  5690.                     (expand-file-name default-directory))))
  5691.              (assoc as-dir dired-subdir-alist)))
  5692.         (setq result (cons buff result))))
  5693.     ;; else buffer is killed - clean up:
  5694.     (setq dired-buffers (delq elt dired-buffers))))
  5695.     (or dired-buffers (dired-remove-from-file-name-handler-alist))
  5696.     result))
  5697.  
  5698. (defun dired-advertise ()
  5699.   ;; Advertise in variable `dired-buffers' that we dired `default-directory'.
  5700.   ;; With wildcards we actually advertise too much.
  5701.   ;; Also makes sure that we are installed in the file-name-handler-alist
  5702.   (prog1
  5703.       (let ((ddir (expand-file-name default-directory)))
  5704.     (if (memq (current-buffer) (dired-buffers-for-dir ddir))
  5705.         t                ; we have already advertised ourselves
  5706.       (setq dired-buffers
  5707.         (cons (cons ddir (current-buffer))
  5708.               dired-buffers))))
  5709.     ;; Do this last, otherwise the call to dired-buffers-for-dir will
  5710.     ;; remove dired-handler-fn from the file-name-handler-alist.
  5711.     ;; Strictly speaking, we only need to do this in th else branch of
  5712.     ;; the if statement.  We do it unconditionally as a sanity check.
  5713.     (dired-check-file-name-handler-alist)))
  5714.  
  5715. (defun dired-unadvertise (dir)
  5716.   ;; Remove DIR from the buffer alist in variable dired-buffers.
  5717.   ;; This has the effect of removing any buffer whose main directory is DIR.
  5718.   ;; It does not affect buffers in which DIR is a subdir.
  5719.   ;; Removing is also done as a side-effect in dired-buffer-for-dir.
  5720.   (setq dired-buffers
  5721.       (delq (assoc dir dired-buffers) dired-buffers))
  5722.   ;; If there are no more dired buffers, we are no longer needed in the
  5723.   ;; file-name-handler-alist.
  5724.   (or dired-buffers (dired-remove-from-file-name-handler-alist)))
  5725.  
  5726. (defun dired-unadvertise-current-buffer ()
  5727.   ;; Remove all references to the current buffer in dired-buffers.
  5728.   (setq dired-buffers
  5729.     (delq nil
  5730.           (mapcar
  5731.            (function
  5732.         (lambda (x)
  5733.           (and (not (eq (current-buffer) (cdr x))) x)))
  5734.            dired-buffers)))
  5735.   ;; If there are no more dired buffers, we are no longer needed in the
  5736.   ;; file-name-handler-alist.
  5737.   (or dired-buffers (dired-remove-from-file-name-handler-alist)))
  5738.  
  5739. (defun dired-fun-in-all-buffers (directory fun &rest args)
  5740.   ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
  5741.   ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
  5742.   (let* ((buf-list (dired-buffers-for-dir directory))
  5743.      (obuf (current-buffer))
  5744.      (owin (selected-window))
  5745.      (win owin)
  5746.      buf windows success-list)
  5747.     (if buf-list
  5748.     (unwind-protect
  5749.         (progn
  5750.           (while (not (eq (setq win (next-window win)) owin))
  5751.         (and (memq (setq buf (window-buffer win)) buf-list)
  5752.              (progn
  5753.                (set-buffer buf)
  5754.                (= (point) (window-point win)))
  5755.              (setq windows (cons win windows))))
  5756.           (while buf-list
  5757.         (setq buf (car buf-list)
  5758.               buf-list (cdr buf-list))
  5759.         (set-buffer buf)
  5760.         (if (apply fun args)
  5761.             (setq success-list (cons (buffer-name buf) success-list))))
  5762.           ;; dired-save-excursion prevents lossage of save-excursion
  5763.           ;; for point.  However, if dired buffers are displayed in
  5764.           ;; other windows, the setting of window-point loses, and
  5765.           ;; drags the point with it.  This should fix this.
  5766.           (while windows
  5767.         (condition-case nil
  5768.             (progn
  5769.               (set-buffer (window-buffer (setq win (car windows))))
  5770.               (set-window-point win (point)))
  5771.           (error nil))
  5772.         (setq windows (cdr windows))))
  5773.       (set-buffer obuf)))
  5774.     success-list))
  5775.  
  5776. (defun dired-find-file-place (subdir file)
  5777.   ;; Finds a position to insert in SUBDIR FILE. If it can't find SUBDIR,
  5778.   ;; returns nil.
  5779.   (let ((sort (dired-sort-type dired-internal-switches))
  5780.     (rev (memq ?r (nth 3 (assoc subdir dired-subdir-alist)))))
  5781.     (cond
  5782.      ((eq sort 'name)
  5783.       (if (dired-goto-subdir subdir)
  5784.       (let ((max (dired-subdir-max))
  5785.         start end found)
  5786.         (if (dired-goto-next-file)
  5787.         (progn
  5788.           (skip-chars-forward "^\n\r")
  5789.           (setq start (point))
  5790.           (goto-char (setq end max))
  5791.           (forward-char -1)
  5792.           (skip-chars-backward "^\n\r")
  5793.           ;; This loop must find a file.  At the very least, it will
  5794.           ;; find the one found previously.
  5795.           (while (not found)
  5796.             (if (save-excursion (dired-move-to-filename nil (point)))
  5797.             (setq found t)
  5798.               (setq end (point))
  5799.               (forward-char -1)
  5800.               (skip-chars-backward "^\n\r")))
  5801.           (if rev
  5802.               (while (< start end)
  5803.             (goto-char (/ (+ start end) 2))
  5804.             (if (dired-file-name-lessp
  5805.                  (or (dired-get-filename 'no-dir t)
  5806.                  (error
  5807.                   "Error in dired-find-file-place"))
  5808.                  file)
  5809.                 (setq end (progn
  5810.                     (skip-chars-backward "^\n\r")
  5811.                     (point)))
  5812.               (setq start (progn
  5813.                     (skip-chars-forward "^\n\r")
  5814.                     (forward-char 1)
  5815.                     (skip-chars-forward "^\n\r")
  5816.                     (point)))))
  5817.             (while (< start end)
  5818.               (goto-char (/ (+ start end) 2))
  5819.               (if (dired-file-name-lessp
  5820.                file
  5821.                (or (dired-get-filename 'no-dir t)
  5822.                    (error
  5823.                 "Error in dired-find-file-place")))
  5824.               (setq end (progn
  5825.                     (skip-chars-backward "^\n\r")
  5826.                     (point)))
  5827.             (setq start (progn
  5828.                       (skip-chars-forward "^\n\r")
  5829.                       (forward-char 1)
  5830.                       (skip-chars-forward "^\n\r")
  5831.                       (point))))))
  5832.           (goto-char end))
  5833.           (goto-char max))
  5834.         t)))
  5835.      ((eq sort 'date)
  5836.       (if (dired-goto-subdir subdir)
  5837.       (if rev
  5838.           (goto-char (dired-subdir-max))
  5839.         (dired-goto-next-file)
  5840.         t)))
  5841.      ;; Put in support for other sorting types.
  5842.      (t
  5843.       (if (string-equal (dired-current-directory) subdir)
  5844.       (progn
  5845.         ;; We are already where we should be, except when
  5846.         ;; point is before the subdir line or its total line.
  5847.         (or (save-excursion (beginning-of-line) (dired-move-to-filename))
  5848.         (dired-goto-next-nontrivial-file)) ; in the header somewhere
  5849.         t) ; return t, for found.
  5850.     (if (dired-goto-subdir subdir)
  5851.         (progn
  5852.           (dired-goto-next-nontrivial-file)
  5853.           t)))))))
  5854.  
  5855. (defun dired-add-entry (filename &optional marker-char inplace)
  5856.   ;; Add a new entry for FILENAME, optionally marking it
  5857.   ;; with MARKER-CHAR (a character, else dired-marker-char is used).
  5858.   ;; Hidden subdirs are exposed if a file is added there.
  5859.   ;; 
  5860.   ;; This function now adds the new entry at the END of the previous line,
  5861.   ;; not the beginning of the current line.
  5862.   ;; Logically, we now think of the `newline' associated
  5863.   ;; with a fileline, as the one at the beginning of the line, not the end.
  5864.   ;; This makes it easier to keep track of omitted files.
  5865.   ;; 
  5866.   ;; Uses dired-save-excursion, so that it doesn't move the
  5867.   ;; point around. Especially important when it runs asynch.
  5868.   ;; 
  5869.   ;; If there is already an entry, delete the existing one before adding a
  5870.   ;; new one.  In this case, doesn't remember its mark.  Use
  5871.   ;; dired-update-file-line for that.
  5872.   ;; 
  5873.   ;; If INPLACE eq 'relist, then the new entry is put in the
  5874.   ;; same place as the old, if there was an old entry.
  5875.   ;; If INPLACE is t, then the file entry is put on the line
  5876.   ;; currently containing the point.  Otherwise, dired-find-file-place
  5877.   ;; attempts to determine where to put the file.
  5878.  
  5879.   (setq filename (directory-file-name filename))
  5880.   (dired-save-excursion
  5881.     (let ((oentry (save-excursion (dired-goto-file filename)))
  5882.       (directory (file-name-directory filename))
  5883.       (file-nodir (file-name-nondirectory filename))
  5884.       buffer-read-only)
  5885.       (if oentry
  5886.       ;; Remove old entry
  5887.       (let ((opoint (point)))
  5888.         (goto-char oentry)
  5889.         (delete-region (save-excursion
  5890.                  (skip-chars-backward "^\r\n")
  5891.                  (dired-update-marker-counters (following-char) t)
  5892.                  (1- (point)))
  5893.                (progn
  5894.                  (skip-chars-forward "^\r\n")
  5895.                  (point)))
  5896.         ;; Move to right place to replace deleted line.
  5897.         (cond ((eq inplace 'relist) (forward-char 1))
  5898.           ((eq inplace t) (goto-char opoint)))
  5899.         (dired-update-mode-line-modified)))
  5900.       (if (or (eq inplace t)
  5901.           (and oentry (eq inplace 'relist))
  5902.           ;; Tries to move the point to the right place.
  5903.           ;; Returns t on success.
  5904.           (dired-find-file-place directory file-nodir))
  5905.       (let ((switches (dired-make-switches-string
  5906.                (cons ?d dired-internal-switches)))
  5907.         b-of-l)
  5908.         ;; Bind marker-char now, in case we are working asynch and
  5909.         ;; dired-marker-char changes in the meantime.
  5910.         (if (and marker-char (not (characterp marker-char)))
  5911.         (setq marker-char dired-marker-char))
  5912.         ;; since we insert at the end of a line,
  5913.         ;; backup to the end of the previous line.
  5914.         (skip-chars-backward "^\n\r")
  5915.         (forward-char -1)
  5916.         (setq b-of-l (point))
  5917.         (if (and (featurep 'efs-dired) efs-dired-host-type)
  5918.         ;; insert asynch
  5919.         ;; we call the efs version explicitly here,
  5920.         ;; rather than let the handler-alist work for us
  5921.         ;; because we want to pass extra args.
  5922.         ;; Is there a cleaner way to do this?
  5923.         (efs-insert-directory filename ; don't expand `.' !
  5924.                       switches nil nil
  5925.                       t ; nowait
  5926.                       marker-char)
  5927.           (let ((insert-directory-program dired-ls-program))
  5928.         (insert-directory filename switches nil nil))
  5929.           (dired-after-add-entry b-of-l marker-char))
  5930.         (if dired-verify-modtimes
  5931.         (dired-set-file-modtime directory dired-subdir-alist))
  5932.         t))))) ; return t on success, else nil.
  5933.  
  5934. (defun dired-after-add-entry (start marker-char)
  5935.   ;; Does the cleanup of a dired entry after listing it.
  5936.   ;; START is the start of the new listing-line.
  5937.   ;; This is a separate function for the sake of efs.
  5938.   (save-excursion
  5939.     (goto-char start)
  5940.     ;; we make sure that the new line is bracketted by new-lines
  5941.     ;; so the user doesn't need to use voodoo in the
  5942.     ;; after-readin-hook.
  5943.     (insert ?\n)
  5944.     (dired-add-entry-do-indentation marker-char)
  5945.     (let* ((beg (dired-manual-move-to-filename t))
  5946.        ;; error for strange output
  5947.        (end (dired-manual-move-to-end-of-filename))
  5948.        (filename (buffer-substring beg end)))
  5949.       ;; We want to have the non-directory part only.
  5950.       (delete-region beg end)
  5951.       ;; Any markers pointing to the beginning of the filename, will
  5952.       ;; still point there after this insertion. Should keep
  5953.       ;; save-excursion from losing.
  5954.       (setq beg (point))
  5955.       (insert (file-name-nondirectory filename))
  5956.       (dired-insert-set-properties beg (point))
  5957.       (dired-move-to-filename))
  5958.     ;; The subdir-alist is not affected so we can run it right now.
  5959.     (let ((omit (dired-current-subdir-omitted-p))
  5960.       (hide (dired-subdir-hidden-p (dired-current-directory))))
  5961.       (if (or dired-after-readin-hook omit hide)
  5962.       (save-excursion
  5963.         (save-restriction
  5964.           ;; Use start so that we get the new-line at
  5965.           ;; the beginning of the line in case we want
  5966.           ;; to hide the file. Don't need to test (bobp)
  5967.           ;; here, since we never add a file at
  5968.           ;; the beginning of the buffer.
  5969.           (narrow-to-region start
  5970.                 (save-excursion (forward-line 1) (point)))
  5971.           (run-hooks 'dired-after-readin-hook)
  5972.           (if omit
  5973.           (let ((dired-omit-silent (or dired-omit-silent 0)))
  5974.             (dired-omit-region (point-min) (point-max)
  5975.                        (dired-omit-regexp))))
  5976.           (if hide
  5977.           (subst-char-in-region (point-min) (1- (point-max))
  5978.                     ?\n ?\r))))))
  5979.     ;; clobber the extra newline at the end of the line
  5980.     (end-of-line)
  5981.     (delete-char 1)))
  5982.  
  5983. ;; This is a separate function for the sake of nested dired format.
  5984. (defun dired-add-entry-do-indentation (marker-char)
  5985.   ;; two spaces or a marker plus a space:
  5986.   (insert (if marker-char
  5987.           (let ((char (if (characterp marker-char)
  5988.                   marker-char
  5989.                 dired-marker-char)))
  5990.         (dired-update-marker-counters char)
  5991.         (dired-update-mode-line-modified)
  5992.         char)
  5993.         ?\040)
  5994.       ?\040))
  5995.  
  5996. (defun dired-remove-file (file)
  5997.   (let ((alist dired-buffers)
  5998.     buff)
  5999.     (save-excursion
  6000.       (while alist
  6001.     (setq buff (cdr (car alist)))
  6002.     (if (buffer-name buff)
  6003.         (progn
  6004.           (set-buffer buff)
  6005.           (dired-remove-entry file))
  6006.       (setq dired-buffers (delq (car alist) dired-buffers)))
  6007.     (setq alist (cdr alist))))
  6008.     (or dired-buffers (dired-remove-from-file-name-handler-alist))))
  6009.  
  6010. (defun dired-remove-entry (file)
  6011.   (let ((ddir (expand-file-name default-directory))
  6012.     (dirname (file-name-as-directory file)))
  6013.     (if (dired-in-this-tree ddir dirname)
  6014.     (if (or (memq 'kill-dired-buffer dired-no-confirm)
  6015.         (y-or-n-p (format "Kill dired buffer %s for %s, too? "
  6016.                   (buffer-name) dired-directory)))
  6017.         (kill-buffer (current-buffer)))
  6018.       (if (dired-in-this-tree file ddir)
  6019.       (let ((alist dired-subdir-alist))
  6020.         (while alist
  6021.           (if (dired-in-this-tree (car (car alist)) dirname)
  6022.           (save-excursion
  6023.             (goto-char (dired-get-subdir-min (car alist)))
  6024.             (dired-kill-subdir)))
  6025.           (setq alist (cdr alist)))
  6026.         (dired-save-excursion
  6027.           (and (dired-goto-file file)
  6028.            (let (buffer-read-only)
  6029.              (delete-region
  6030.               (progn (skip-chars-backward "^\n\r")
  6031.                  (or (memq (following-char) '(\n \r ?\ ))
  6032.                  (progn
  6033.                    (dired-update-marker-counters
  6034.                     (following-char) t)
  6035.                    (dired-update-mode-line-modified)))
  6036.                  (1- (point)))
  6037.               (progn (skip-chars-forward "^\n\r") (point)))
  6038.              (if dired-verify-modtimes
  6039.              (dired-set-file-modtime
  6040.               (file-name-directory (directory-file-name file))
  6041.               dired-subdir-alist))))))))))
  6042.  
  6043. (defun dired-add-file (filename &optional marker-char)
  6044.   (dired-fun-in-all-buffers
  6045.    (file-name-directory filename)
  6046.    (function dired-add-entry) filename marker-char))
  6047.  
  6048. (defun dired-relist-file (file)
  6049.   (dired-uncache file nil)
  6050.   (dired-fun-in-all-buffers (file-name-directory file)
  6051.                 (function dired-relist-entry) file))
  6052.  
  6053. (defun dired-relist-entry (file)
  6054.   ;; Relist the line for FILE, or just add it if it did not exist.
  6055.   ;; FILE must be an absolute pathname.
  6056.   (let* ((file (directory-file-name file))
  6057.      (directory (file-name-directory file))
  6058.      (dd (expand-file-name default-directory)))
  6059.     (if (assoc directory dired-subdir-alist)
  6060.     (if (or
  6061.          ;; Not a wildcard
  6062.          (equal dd dired-directory)
  6063.          ;; Not top-level
  6064.          (not (string-equal directory dd))
  6065.          (and (string-equal directory
  6066.                 (if (consp dired-directory)
  6067.                     (file-name-as-directory
  6068.                      (car dired-directory))
  6069.                   (file-name-directory dired-directory)))
  6070.           (dired-file-in-wildcard-p dired-directory file)))
  6071.         (let ((marker (save-excursion
  6072.                 (and (dired-goto-file file)
  6073.                  (dired-file-marker file)))))
  6074.           ;; recompute omission
  6075.           (if (eq marker dired-omit-marker-char)
  6076.           (setq marker nil))
  6077.           (dired-add-entry file marker 'relist))
  6078.       ;; At least tell dired that we considered updating the buffer.
  6079.       (if dired-verify-modtimes
  6080.           (dired-set-file-modtime directory dired-subdir-alist))))))
  6081.  
  6082. (defun dired-file-in-wildcard-p (wildcard file)
  6083.   ;; Return t if a file is part of the listing for wildcard.
  6084.   ;; File should be the non-directory part only.
  6085.   ;; This version is slow, but meticulously correct.  Is it worth it?
  6086.   (if (consp wildcard)
  6087.       (let ((files (cdr wildcard))
  6088.         (dir (car wildcard))
  6089.         yep)
  6090.     (while (and files (not yep))
  6091.       (setq yep (string-equal file (expand-file-name (car files) dir))
  6092.         files (cdr files)))
  6093.     yep)
  6094.     (let ((err-buff
  6095.        (let ((default-major-mode 'fundamental-mode))
  6096.          (get-buffer-create " *dired-check-process output*")))
  6097.       (dir default-directory)
  6098.       (process-connection-type nil))
  6099.       (save-excursion
  6100.     (set-buffer err-buff)
  6101.     (erase-buffer)
  6102.     (setq default-directory dir)
  6103.     (call-process shell-file-name nil t nil "-c"
  6104.             (concat dired-ls-program " -d " wildcard " | "
  6105.                 "egrep '(^|/)" file "$'"))
  6106.     (/= (buffer-size) 0)))))
  6107.  
  6108. ;; The difference between dired-add-file and dired-relist-file is that
  6109. ;; the former creates the entry with a specific marker.  The later preserves
  6110. ;; existing markers on a per buffer basis.  This is not the same as
  6111. ;; giving dired-create-files a marker of t, which uses a marker in a specific
  6112. ;; buffer to determine the marker for file line creation in all buffers.
  6113.  
  6114.  
  6115. ;;;; ----------------------------------------------------------------
  6116. ;;;; Applying Lisp functions to marked files.
  6117. ;;;; ----------------------------------------------------------------
  6118.  
  6119. ;;; Running tags commands on marked files.
  6120. ;;
  6121. ;; Written 8/30/93 by Roland McGrath <roland@gnu.ai.mit.edu>.
  6122. ;; Requires tags.el as distributed with GNU Emacs 19.23, or later.
  6123.  
  6124. (defun dired-do-tags-search (regexp)
  6125.   "Search through all marked files for a match for REGEXP.
  6126. Stops when a match is found.
  6127. To continue searching for next match, use command \\[tags-loop-continue]."
  6128.   (interactive "sSearch marked files (regexp): ")
  6129.   (tags-search regexp '(dired-get-marked-files)))
  6130.  
  6131. (defun dired-do-tags-query-replace (from to &optional delimited)
  6132.   "Query-replace-regexp FROM with TO through all marked files.
  6133. Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
  6134. If you exit (\\[keyboard-quit] or ESC), you can resume the query-replace
  6135. with the command \\[tags-loop-continue]."
  6136.   (interactive
  6137.    "sQuery replace in marked files (regexp): \nsQuery replace %s by: \nP")
  6138.   (tags-query-replace from to delimited '(dired-get-marked-files)))
  6139.  
  6140. ;;; byte compiling
  6141.  
  6142. (defun dired-byte-compile ()
  6143.   ;; Return nil for success, offending file name else.
  6144.   (let* ((filename (dired-get-filename))
  6145.      buffer-read-only failure)
  6146.     (condition-case err
  6147.     (save-excursion (byte-compile-file filename))
  6148.       (error
  6149.        (setq failure err)))
  6150.     ;; We should not need to update any file lines, as this will have
  6151.     ;; already been done by after-write-region-hook.
  6152.     (and failure
  6153.      (progn
  6154.        (dired-log (buffer-name (current-buffer))
  6155.               "Byte compile error for %s:\n%s\n" filename failure)
  6156.        (dired-make-relative filename)))))
  6157.  
  6158. (defun dired-do-byte-compile (&optional arg)
  6159.   "Byte compile marked (or next ARG) Emacs lisp files."
  6160.   (interactive "P")
  6161.   (dired-map-over-marks-check (function dired-byte-compile) arg
  6162.                   'byte-compile "byte-compile" t))
  6163.  
  6164. ;;; loading
  6165.  
  6166. (defun dired-load ()
  6167.   ;; Return nil for success, offending file name else.
  6168.   (let ((file (dired-get-filename)) failure)
  6169.     (condition-case err
  6170.       (load file nil nil t)
  6171.       (error (setq failure err)))
  6172.     (if (not failure)
  6173.     nil
  6174.       (dired-log (buffer-name (current-buffer))
  6175.          "Load error for %s:\n%s\n" file failure)
  6176.       (dired-make-relative file))))
  6177.  
  6178. (defun dired-do-load (&optional arg)
  6179.   "Load the marked (or next ARG) Emacs lisp files."
  6180.   (interactive "P")
  6181.   (dired-map-over-marks-check (function dired-load) arg 'load "load" t))
  6182.  
  6183.  
  6184. ;;;; ----------------------------------------------------------------
  6185. ;;;; File Name Handler Alist
  6186. ;;;; ----------------------------------------------------------------
  6187. ;;;
  6188. ;;;  Make sure that I/O functions maintain dired buffers.
  6189.  
  6190. (defun dired-remove-from-file-name-handler-alist ()
  6191.   ;; Remove dired from the file-name-handler-alist
  6192.   (setq file-name-handler-alist
  6193.     (delq nil
  6194.           (mapcar
  6195.            (function
  6196.         (lambda (x)
  6197.           (and (not (eq (cdr x) 'dired-handler-fn))
  6198.                x)))
  6199.            file-name-handler-alist))))
  6200.  
  6201. (defun dired-check-file-name-handler-alist ()
  6202.   ;; Verify that dired is installed as the first item in the alist
  6203.   (and dired-refresh-automatically
  6204.        (or (eq (cdr (car file-name-handler-alist)) 'dired-handler-fn)
  6205.        (setq file-name-handler-alist
  6206.          (cons
  6207.           '("." . dired-handler-fn)
  6208.           (dired-remove-from-file-name-handler-alist))))))
  6209.  
  6210. (defun dired-handler-fn (op &rest args)
  6211.   ;; Function to update dired buffers after I/O.
  6212.   (prog1
  6213.       (let ((inhibit-file-name-handlers
  6214.          (cons 'dired-handler-fn
  6215.            (and (eq inhibit-file-name-operation op)
  6216.             inhibit-file-name-handlers)))
  6217.         (inhibit-file-name-operation op))
  6218.     (apply op args))
  6219.     (let ((dired-omit-silent t)
  6220.       (hf (get op 'dired)))
  6221.       (and hf (funcall hf args)))))
  6222.  
  6223. (defun dired-handler-fn-1 (args)
  6224.   (let ((to (expand-file-name (nth 1 args))))
  6225.     (or (member to dired-unhandle-add-files)
  6226.     (dired-relist-file to))))
  6227.  
  6228. (defun dired-handler-fn-2 (args)
  6229.   (let ((from (expand-file-name (car args)))
  6230.     (to (expand-file-name (nth 1 args))))
  6231.     ;; Don't remove the original entry if making backups.
  6232.     ;; Otherwise we lose marks.  I'm not completely happy with the
  6233.     ;; logic here.
  6234.     (or (and
  6235.      (eq (nth 2 args) t) ; backups always have OK-IF-OVERWRITE t
  6236.      (string-equal (car (find-backup-file-name from)) to))
  6237.     (dired-remove-file from))
  6238.     (or (member to dired-unhandle-add-files)
  6239.     (dired-relist-file to))))
  6240.  
  6241. (defun dired-handler-fn-3 (args)
  6242.   (let ((to (expand-file-name (nth 2 args))))
  6243.     (or (member to dired-unhandle-add-files)
  6244.     (dired-relist-file to))))
  6245.  
  6246. (defun dired-handler-fn-4 (args)
  6247.   (dired-remove-file (expand-file-name (car args))))
  6248.  
  6249. (defun dired-handler-fn-5 (args)
  6250.   (let ((to (expand-file-name (car args))))
  6251.     (or (member to dired-unhandle-add-files)
  6252.     (dired-relist-file to))))
  6253.  
  6254. (defun dired-handler-fn-6 (args)
  6255.   (let ((to (expand-file-name (nth 1 args)))
  6256.     (old (expand-file-name (car args))))
  6257.     (or (member to dired-unhandle-add-files)
  6258.     (dired-relist-file to))
  6259.     (dired-relist-file old)))
  6260.  
  6261. (put 'copy-file 'dired 'dired-handler-fn-1)
  6262. (put 'dired-make-relative-symlink 'dired 'dired-handler-fn-1)
  6263. (put 'make-symbolic-link 'dired 'dired-handler-fn-1)
  6264. (put 'add-name-to-file 'dired 'dired-handler-fn-6)
  6265. (put 'rename-file 'dired 'dired-handler-fn-2)
  6266. (put 'write-region 'dired 'dired-handler-fn-3)
  6267. (put 'delete-file 'dired 'dired-handler-fn-4)
  6268. (put 'delete-directory 'dired 'dired-handler-fn-4)
  6269. (put 'dired-recursive-delete-directory 'dired 'dired-handler-fn-4)
  6270. (put 'make-directory-internal 'dired 'dired-handler-fn-5)
  6271. (put 'set-file-modes 'dired 'dired-handler-fn-5)
  6272.   
  6273. ;;;; ------------------------------------------------------------
  6274. ;;;; Autoload land.
  6275. ;;;; ------------------------------------------------------------
  6276.  
  6277. ;;; Reading mail (dired-xy)
  6278.  
  6279. (autoload 'dired-read-mail "dired-xy"
  6280.       "Reads the current file as a mail folder." t)
  6281. (autoload 'dired-vm "dired-xy" "Run VM on this file." t)
  6282. (autoload 'dired-rmail "dired-xy" "Run RMAIL on this file." t)
  6283.  
  6284. ;;; Virtual dired (dired-vir)
  6285.  
  6286. (autoload 'dired-virtual "dired-vir"
  6287.       "Put this buffer into virtual dired mode." t)
  6288.  
  6289. ;;; Grep (dired-grep)
  6290.  
  6291. (autoload 'dired-do-grep "dired-grep" "Grep marked files for a pattern." t)
  6292.  
  6293. ;;; Doing diffs (dired-diff)
  6294.  
  6295. (autoload 'dired-diff "dired-diff"
  6296.       "Compare file at point with FILE using `diff'." t)
  6297. (autoload 'dired-backup-diff "dired-diff"
  6298.       "Diff this file with its backup file or vice versa." t)
  6299. (autoload 'dired-emerge "dired-diff"
  6300.       "Merge file at point with FILE using `emerge'." t)
  6301. (autoload 'dired-emerge-with-ancestor "dired-diff"
  6302.       "Merge file at point with FILE, using a common ANCESTOR file." t)
  6303. (autoload 'dired-ediff "dired-diff" "Ediff file at point with FILE." t)
  6304. (autoload 'dired-epatch "dired-diff" "Patch file at point using `epatch'." t)
  6305.  
  6306. ;;; Shell commands (dired-shell)
  6307.  
  6308. (autoload 'dired-do-print "dired-shell" "Print the marked (next ARG) files." t)
  6309. (autoload 'dired-run-shell-command "dired-shell" nil)
  6310. (autoload 'dired-do-shell-command "dired-shell"
  6311.       "Run a shell command on the marked (or next ARG) files." t)
  6312. (autoload 'dired-do-background-shell-command "dired-shell"
  6313.       "Run a background shell command on marked (or next ARG) files." t)
  6314.  
  6315. ;;; Commands using regular expressions (dired-rgxp)
  6316.  
  6317. (autoload 'dired-mark-files-regexp "dired-rgxp"
  6318.       "Mark all files whose names match REGEXP." t)
  6319. (autoload 'dired-flag-files-regexp "dired-rgxp"
  6320.       "Flag for deletion all files whose names match REGEXP." t)
  6321. (autoload 'dired-mark-extension "dired-rgxp"
  6322.       "Mark all files whose names have a given extension." t)
  6323. (autoload 'dired-flag-extension "dired-rgxp"
  6324.       "Flag for deletion all files whose names have a given extension." t)
  6325. (autoload 'dired-cleanup "dired-rgxp"
  6326.       "Flag for deletion dispensable files files created by PROGRAM." t)
  6327. (autoload 'dired-do-rename-regexp "dired-rgxp"
  6328.       "Rename marked files whose names match a given regexp." t)
  6329. (autoload 'dired-do-copy-regexp "dired-rgxp"
  6330.       "Copy marked files whose names match a given regexp." t)
  6331. (autoload 'dired-do-hardlink-regexp "dired-rgxp"
  6332.       "Hardlink all marked files whose names match a regexp." t)
  6333. (autoload 'dired-do-symlink "dired-rgxp"
  6334.       "Make a symbolic link to all files whose names match a regexp." t)
  6335. (autoload
  6336.  'dired-do-relsymlink-regexp "dired-rgxp"
  6337.  "Make a relative symbolic link to all files whose names match a regexp." t)
  6338. (autoload 'dired-upcase "dired-rgxp"
  6339.       "Rename all marked (or next ARG) files to upper case." t)
  6340. (autoload 'dired-downcase "dired-rgxp"
  6341.       "Rename all marked (or next ARG) files to lower case." t)
  6342.  
  6343. ;;; Marking files from other buffers (dired-mob)
  6344.  
  6345. (autoload 'dired-mark-files-from-other-dired-buffer "dired-mob"
  6346.       "Mark files which are marked in another dired buffer." t)
  6347. (autoload 'dired-mark-files-compilation-buffer "dired-mob"
  6348.       "Mark the files mentioned in the compilation buffer." t)
  6349.  
  6350. ;;; uuencoding (dired-uu)
  6351.  
  6352. (autoload 'dired-do-uucode "dired-uu" "Uuencode or uudecode marked files." t)
  6353.  
  6354. ;;; Compressing (dired-cmpr)
  6355.  
  6356. (autoload 'dired-do-compress "dired-cmpr"
  6357.       "Compress or uncompress marked files." t)
  6358. (autoload 'dired-compress-subdir-files "dired-cmpr"
  6359.       "Compress uncompressed files in the current subdirectory." t)
  6360.  
  6361.  
  6362. ;;; Marking files according to sexps
  6363.  
  6364. (autoload 'dired-mark-sexp "dired-sex"
  6365.       "Mark files according to an sexpression." t)
  6366.  
  6367. ;;; Help!
  6368.  
  6369. (autoload 'dired-summary "dired-help"
  6370.       "Display summary of basic dired commands in the minibuffer." t)
  6371. (autoload 'dired-describe-mode "dired-help"
  6372.       "Detailed description of dired mode.
  6373. With a prefix, runs the info documentation browser for dired." t)
  6374. (autoload 'dired-apropos "dired-help"
  6375.       "Do command apropos help for dired commands.
  6376. With prefix does apropos help for dired variables." t)
  6377. (autoload 'dired-report-bug "dired-help" "Report a bug for dired." t)
  6378.  
  6379. ;;;; --------------------------------------------------------------
  6380. ;;;; Multi-flavour Emacs support
  6381. ;;;; --------------------------------------------------------------
  6382.  
  6383. (let ((lucid-p (string-match "XEmacs" emacs-version))
  6384.       ver)
  6385.   (or (string-match "^\\([0-9]+\\)\\." emacs-version)
  6386.       (error "Weird emacs version %s" emacs-version))
  6387.   (setq ver (string-to-int (substring emacs-version (match-beginning 1)
  6388.                       (match-end 1))))
  6389.  
  6390.   ;; Reading with history.
  6391.   (if (>= ver 19)
  6392.  
  6393.       (defun dired-read-with-history (prompt initial history)
  6394.     (read-from-minibuffer prompt initial nil nil history))
  6395.     
  6396.     (defun dired-read-with-history (prompt initial history)
  6397.       (let ((minibuffer-history-symbol history)) ; for gmhist
  6398.     (read-string prompt initial))))
  6399.   
  6400.   ;; Completing read with history.
  6401.   (if (>= ver 19)
  6402.  
  6403.       (fset 'dired-completing-read 'completing-read)
  6404.  
  6405.     (defun dired-completing-read (prompt table &optional predicate
  6406.                      require-match initial-input history)
  6407.       (let ((minibuffer-history-symbol history)) ; for gmhist
  6408.     (completing-read prompt table predicate require-match
  6409.              initial-input))))
  6410.   
  6411.   ;; Abbreviating file names.
  6412.   (if lucid-p
  6413.       (fset 'dired-abbreviate-file-name
  6414.         ;; Lemacs has this extra hack-homedir arg
  6415.         (function
  6416.          (lambda (fn)
  6417.            (abbreviate-file-name fn t))))
  6418.     (fset 'dired-abbreviate-file-name 'abbreviate-file-name))
  6419.  
  6420.   ;; Deleting directories
  6421.   ;; Check for pre 19.8 versions of lucid emacs.
  6422.   (if lucid-p
  6423.       (or (fboundp 'delete-directory)
  6424.       (fset 'delete-directory 'remove-directory)))
  6425.   
  6426.   ;; Minibuffers
  6427.   (if (= ver 18)
  6428.     
  6429.       (defun dired-get-active-minibuffer-window ()
  6430.     (and (> (minibuffer-depth) 0)
  6431.          (minibuffer-window)))
  6432.     
  6433.     (defun dired-get-active-minibuffer-window ()
  6434.       (let ((frames (frame-list))
  6435.         win found)
  6436.     (while frames
  6437.       (if (and (setq win (minibuffer-window (car frames)))
  6438.            (minibuffer-window-active-p win))
  6439.           (setq found win
  6440.             frames nil)
  6441.         (setq frames (cdr frames))))
  6442.     found)))
  6443.  
  6444.   ;; Text properties and menus.
  6445.  
  6446.   (cond
  6447.    (lucid-p
  6448.     (require 'dired-xemacs))
  6449.    ((>= ver 19)
  6450.     (require 'dired-fsf))
  6451.    (t
  6452.     ;; text property stuff doesn't work in V18
  6453.     (fset 'dired-insert-set-properties 'ignore)
  6454.     (fset 'dired-remove-text-properties 'ignore)
  6455.     (fset 'dired-set-text-properties 'ignore)
  6456.     (fset 'dired-move-to-filename 'dired-manual-move-to-filename)
  6457.     (fset 'dired-move-to-end-of-filename
  6458.       'dired-manual-move-to-end-of-filename))))
  6459.  
  6460. ;;; MULE
  6461.  
  6462. (if (or (boundp 'MULE) (featurep 'mule)) (load "dired-mule"))
  6463.  
  6464.  
  6465. ;; Run load hook for user customization.
  6466. (run-hooks 'dired-load-hook)
  6467.  
  6468. ;;; end of dired.el
  6469.